简体   繁体   中英

How can I hold the selected element's node by value (and not reference) in Javascript?

I had to remove everything in the body except for images in the DOM. So, this is what I did.

  1. Stored the img tags in the variable.

    var img_nodes = document.getElementsByTagName('img');

  2. Removed every thing inside the body

    var body_node = document.getElementsByTagName('body'); body_node[0].innerHTML = ''

  3. Added the stored img nodes as children

    for each (child in img_nodes){ body.appendChild(child); }

But after I had run body_node[0].innerHTML = '' , the img_nodes became undefined .

I guess that happened because element node was being stored in list as objects (as a reference). How can I save my selected img_nodes objects ?

You could clone the image nodes before clearing the body contents. See the documentation on cloneNode . Example:

var cloned_nodes = [];
for each (child in img_nodes){
    cloned_nodes.push(child.cloneNode(true));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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