我有一个给客户的脚本。客户端可以将其放在其 html 正文中的任何位置。它可以放在 div、td、p 或任何类似的东西之间。
脚本看起来像这样:
<script id="myExample" src="http://www.mydomain.com/example.js" ></script>
现在,在“example.js”中,我想动态地包装我的脚本。
我试过类似的东西:
// create the container div
$("#myExample").wrap('<div></div>');
document.getElementById("myExample").firstChild.setAttribute("id","myExampleContainer");
...但我收到一个错误:
TypeError: document.getElementById(...).firstChild is null
可以用 div 包装当前元素(这是一个 js),并给包装器一个 id 可能吗?
更新:请参阅下面 Musa 的答案。
两种工作解决方案:
// create the container div
$("#myExample").wrap('<div></div>');
document.getElementById("myExample").parentNode.setAttribute("id","myExampleContainer");
...或者:
$("#myExample").wrap('<div id="myExampleContainer"></div>');