如何在JavaScript中添加新元素? [英] How can I append a new element in place in JavaScript?

查看:40
本文介绍了如何在JavaScript中添加新元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个JavaScript脚本,可以将该脚本粘贴到某人的页面上以创建iFrame。我希望该人能够将脚本粘贴到他们希望iFrame出现的位置。

I've created a JavaScript script that can be pasted on someone's page to create an iFrame. I would like for the person to be able to paste the script where they would like the iFrame to appear.

但是,我不知道如何添加DOM。已将iFrame创建到粘贴脚本的位置。它总是将其附加到身体的最底部。

However, I can't figure out how to append the DOM created iFrame to the location where the script has been pasted. It always appends it to the very bottom of the body.

如何附加到位?

推荐答案

嗯。您可以这样做:

document.write("<div id='iframecontainer'></div>");
document.getElementById('iframecontainer').innerHTML = '...';

但这在很多不同的层次上都是丑陋的/错误的。不过,我还没有其他选择。

But that feels ugly/wrong in a lot of different levels. I am not aware of any other alternatives, though.

编辑:实际上,快速的Google搜索显示了此文章,其中讨论了为什么 document.write 很难看,并且是您所在的特定泡菜的不错选择:给您的脚本标记一个ID!

EDIT: Actually, a quick google search revealed this artlcle which discusses why document.write is ugly and a nice alternative for the particular pickle you're in: Give your script tag an ID!

<script id="iframeinserter" src=".."></script>

然后您可以获取对脚本标记的引用并在其之前插入iframe:

And then you can get a reference to the script tag and insert the iframe before it:

var newcontent = document.createElement('iframe'); 
var scr = document.getElementById('iframeinserter'); 
scr.parentNode.insertBefore(newcontent, scr); 

这篇关于如何在JavaScript中添加新元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆