简体   繁体   中英

How to append a text or number range to a div using javascript?

I inherited a JS file that goes like this:

    var id1 = document.getElementById("id1");
    var id2 = document.getElementById("id2");
    var id3 = document.getElementById("id3");
    var id4 = document.getElementById("id4"); //etc etc.

I was wondering if there is an easier way using plain Javascript to append a number to an id that has the same name, rather than listing each one out line by line.

Please advise.

Thanks!

 var nodes = []; var find = 6; for (var i = 1; i <= 6; i++) { nodes.push(document.getElementById('id' + i)); } console.log(nodes); 
 <div id="id1"></div> <div id="id2"></div> <div id="id3"></div> <div id="id4"></div> <div id="id5"></div> <div id="id6"></div> 


A more robust solution:

Use querySelectorAll to select elements that have id's that begin with id , then filter out the results that do not match id followed by a number.

 var nodes = document.querySelectorAll('[id^="id"]'); nodes = [].slice.call(nodes).filter(function(node) { return /id\\d+/.test(node.id); }); console.log(nodes); 
 <div id="id1"></div> <div id="id2"></div> <div id="id3"></div> <div id="id4"></div> <div id="id5"></div> <div id="id6"></div> <!-- This node should not be included --> <div id="idea"></div> 

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