简体   繁体   English

向动态创建的元素添加ID

[英]Add an id to a dynamically created element

I'm trying to add an id to an element that I create dynamically using javascripts' document.createElement() method. 我正在尝试向使用javascripts的document.createElement()方法动态创建的元素添加ID。 Basically I want to create an iframe in my html document and at the same time give that newly created element an id. 基本上,我想在html文档中创建一个iframe,同时为该新创建的元素提供一个ID。

Here's my code so far. 到目前为止,这是我的代码。 I've figured out how to put the element in the DOM and all that, i just need the id. 我已经弄清楚了如何将元素放入DOM等等,我只需要id。

function build(content){
      var newIframe = document.createElement("iframe");

      var newContent = document.createTextNode("Hello World!");

      newIframe.appendChild(newContent);

      var element = document.getElementById("container");
      document.body.insertBefore(newIframe, element);

      document.getElementsByTagName("iframe").id = "active";
    };

As you can probably see, I have tried to give it an id at the very end. 您可能会看到,我尝试在最后给它一个ID。 Problem is, it doesn't work. 问题是,它不起作用。

So if anyone has any idea of what is wrong here, or an alternative way of doing what I want to do, please feel free to express yourself. 因此,如果有人对这里的问题有任何想法,或者有另一种做我想做的事情的方法,请随时表达自己。 Many thanks! 非常感谢!

Just add an attribute ( id is an attribute) to that element directly , like this: 只需直接向该元素添加一个属性( id是一个属性),就像这样:

var newIframe = document.createElement("iframe");
newIframe.id = 'active';

... although it looks quite strange to have id equal to active (too generic for a unique identifier). ...尽管id等于active看起来很奇怪(对于唯一标识符来说太通用了)。

Your current approach doesn't work because document.getElementsByTagName("iframe") returns a collection of elements - NodeList or HTMLCollection (it's browser-dependant ). 您当前的方法是行不通的,因为document.getElementsByTagName("iframe")返回元素的集合- NodeListHTMLCollection (它的浏览器相关的 )。 While you can assign a value to its id property, it won't do what you mean to. 尽管您可以为其id属性分配一个值,但它不会执行您的意图。 To make it work, you can adjust it this way: 要使其正常工作,您可以通过以下方式进行调整:

document.getElementsByTagName("iframe")[0].id = "active";

... but, as shown above, there's a better way. ...但是,如上所述,有更好的方法。

newIFrame.setAttribute("id", "something");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM