1

If I create a new HTML element using document.createElement, but I do not add it to the DOM, is there a way to find it? As this is a method of document, it seems somewhat logical that it might become property of document.

Example:

(function(){
    document.createElement("a");
})();

console.log(document.getElementsByTagName("a").length); // -> 0

I understand why the above example doesn't work. Is there an alternative?

4

2 回答 2

3

您只是创建了一些元素,而没有将它们插入到 DOM 中。

如果您想知道它们有多少,则需要存储它们。

var myElements = []:
var elem = document.createElement("a");
myElements.push(elem);
myElements.length; // use their length for your needs
于 2013-08-07T13:53:55.507 回答
1

If you are creating elements in several different functions then you need to update the global array:

var linkElements = []; //declared in global

function addLinkElements()
{
    var link = document.createElement("a");

    // add link element to global array
    linkElements.push(link);

    // total link elements
    alert( "Total anchors: " + linkElements.length + document.getElementsByTagName("a") );
}

Note: Remember to remove update the array in all functions adding these link elements.

hope that helps.

于 2013-08-07T14:00:06.683 回答