简体   繁体   中英

How can I log the number of a specific DOM element into the console?

I'm trying to log the number of elements in a html document that have the id "para" here is the code so far

window.addEventListener("load",init);
function init(){

        var b = document.getElementById("para");

        console.log(b);

}

so far it will only log the element itself and not the number of them in the html document

   var b = document.getElementById("para");

Note the singular in this class, it only returns a single element (or null).

If your document is well-formed, there will only be ONE element with the ID of para . That is one of the things that separates IDs from classes.

You have two solutions.

  • Get away from using ID and use either class or data-* attributes
  • use document.querySelectorAll("#para")

Of the two, I recommend fixing your HTML.

Demo code in reference to a comment

 var list = document.querySelectorAll("#test-span"); console.log(list.length); 
 <span id="test-span">1</span> <span id="test-span">1</span> <span id="test-span">1</span> 

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