0

例如,我有这样的 html 元素:

<div>
    <script type="text/javascript" src="js/embed.js"></script>
</div>

我应该如何在 embed.js 中编写以在上面的 div 中创建一个新的 div,而不使用 jquery ?

非常感谢

4

4 回答 4

2

听起来您想要的结果类似于以下标记:

<div>This is the new div</div>
<div>
    <script type="text/javascript" src="js/embed.js"></script>
</div>

如果是这种情况,您将需要:

  1. 找到src等于 'js/embed.js'的脚本标签
  2. 选择父级(div容器)
  3. 用于insertBefore()添加新的div

如果这一切都属实,代码将如下所示:

var parent,
    i = 0,
    scripts = document.scripts,
    newDiv =document.createElement('div');

newDiv.innerHTML = "This is the new div";

for (var i = 0; i < scripts.length; i++) {
    if (scripts[i].getAttribute('src') === 'js/embed.js') {
        parent = scripts[i].parentNode;
        parent.parentNode.insertBefore(newDiv, parent)
    }
}

jsFiddle

如果您希望您的标记是这样的:

<div>
    <div>This is the new div</div>
    <script type="text/javascript" src="js/embed.js"></script>
</div>

然后使用这个:

var i = 0,
    scripts = document.scripts,
    newDiv = document.createElement('div');

newDiv.innerHTML = "This is the new div";

for (i = 0; i < scripts.length; i++) {
    if (scripts[i].getAttribute('src') === 'js/embed.js') {
        scripts[i].parentNode.insertBefore(newDiv, scripts[i])
    }
}

小提琴

于 2013-05-27T11:40:47.997 回答
1

Just use document.write():

document.write('<div></div>');

document.write() writes the output at the position where it is being executed, in your case within the first <div>.

于 2013-05-27T11:23:43.467 回答
1

以下可能有效:

<div id="mydiv">
</div>

function addDiv()
{
  document.getElementById("mydiv").innerHTML = "<div>some other text</div>"
}
于 2013-05-27T11:25:33.573 回答
0
document.querySelector("div script[src='js/embed.js']").parentElement.appendChild(document.createElement("div"));
于 2013-05-27T11:50:14.897 回答