Alternatives to document.write

喜欢而已 提交于 2019-11-29 12:21:51
bfavaretto

This just occurred to me, and I remembered your question: the script code can find the script block it is in, so you can traverse the DOM from there. The current script block will be the last one in the DOM at the moment (the DOM still being parsed when the code runs).

By locating the current script block, you can find its parent element, and add new elements anywhere:

<!doctype html>
<html>
    <head>
        <style>
        .parent .before { color: red; }
        .parent .after { color: blue; }
        </style>
    </head>
    <body>
        <script></script>
        <div class="parent">
            <span>before script block</span>
            <script>
            var s = document.getElementsByTagName('script');
            var here = s[s.length-1];

            var red = document.createElement("p");
            red.className = 'before';
            red.innerHTML = "red text";
            here.parentNode.insertBefore(red, here);

            var blue = document.createElement("p");
            blue.className = 'after';
            blue.innerHTML = "blue text";
            here.parentNode.appendChild(blue);
            </script>
            <span>after script block</span>
        </div>
        <script></script>
    </body>
</html>​

http://jsfiddle.net/gFyK9/2/

Note the "blue text" span will be inserted before the "after script block" span. That's because the "after" span does not exist in the DOM at the moment appendChild is called.


However there's a very simple way to make this fail.

There is no alternative to this method. This is the only way that the script can find the width of the element that it is nested in without knowing anything about the DOM that it is loaded into.

Using document.write() when used appropriately is legitimate. Although, appending a new element to the DOM is preferable, it is not always an available option.

if you know which child element it is you can use the param nth child in jquery. otherwise youll need to iterate through them with each()

Create and append the child like this:

var el = document.createElement('div');
el.id='id';
document.body.appendChild(el);

However I'm not really sure what you want to do with this to get the width of whatever, it will probably return 0.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!