尝试使用 js 附加到元素?

发布于 2024-07-27 13:27:05 字数 156 浏览 2 评论 0原文

我试图向页面上的所有 添加一段 html 片段。 我知道我可以通过标签名称访问元素并且可以更改元素,但我可以简单地附加到它吗?

另外,我想将其添加到每个标签的内容中,而不是文档的末尾。 这些方法中哪一个有效?

I am trying to add to all <object>'s on a page a snippet of html. I understand I can access elements by tag name and that I can change the element, but can I simple append to it instead?

In addition, I want to add it to the contents of each tag, not the end of the document. Which of these methods will work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

土豪 2024-08-03 13:27:05

假设没有库...

var elementToAppend = document.createElement(tagName); // Your tag name here

// Set attributes and properties on elementToAppend here with
// elementToAppend.attribute = value (eg elementToAppend.id = "some_id")
// You can then append child text and elements with DOM methods
// (createElement or createTextNode with appendChild)
// or with innerHTML (elementToAppend.innerHTML = "some html string")

var objects = document.getElementsByTagName('object');
for(var i = 0; i < objects.length; i++) {
    elementToAppend = elementToAppend.cloneNode(true);
    objects[i].appendChild(elementToAppend);
}

按照其他答案的建议使用 innerHTMLouterHTML 可能会给您嵌入 的任何内容带来问题>。

Assuming no library...

var elementToAppend = document.createElement(tagName); // Your tag name here

// Set attributes and properties on elementToAppend here with
// elementToAppend.attribute = value (eg elementToAppend.id = "some_id")
// You can then append child text and elements with DOM methods
// (createElement or createTextNode with appendChild)
// or with innerHTML (elementToAppend.innerHTML = "some html string")

var objects = document.getElementsByTagName('object');
for(var i = 0; i < objects.length; i++) {
    elementToAppend = elementToAppend.cloneNode(true);
    objects[i].appendChild(elementToAppend);
}

Using innerHTML or outerHTML as other answers have suggested will likely cause problems for whatever you've embedded with <object>.

蓝咒 2024-08-03 13:27:05

appendChild 就是您要寻找的。

appendChild is what you're looking for.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文