How to count the number of li elements in the list? I have such a code example, but it is wrong, how to edit it?

let li = document.getElementById('ul'); console.log(li.childElementCount); 
 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div> <article> <p>Lorem ipsum dolor sit amet, odio omnesque ius cu, quo ex atqui antiopam. At detracto menandri eos. Duo in causae viderer, graeci <a href="#">reprehendunt</a> has in. Decore <mark>nemore</mark> philosophia te pro, nobis legere causae ex mei, odio putant mentitum ea ius. Vix nostro deserunt explicari eu.</p> </article> </div> <ul> <li><a href="#">Link1</a></li> <li><a href="#">Link2</a></li> <li><a href="#">Link3</a></li> <li><a href="#">Link4</a></li> </ul><span></span> <a href="#">Some link</a> <script src="main.js"></script> </body> </html> 

    2 answers 2

    You confused getElementById with getElementsByTagName

     let li = document.getElementsByTagName('UL')[0]; console.log(li.childElementCount); 
     <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div> <article> <p>Lorem ipsum dolor sit amet, odio omnesque ius cu, quo ex atqui antiopam. At detracto menandri eos. Duo in causae viderer, graeci <a href="#">reprehendunt</a> has in. Decore <mark>nemore</mark> philosophia te pro, nobis legere causae ex mei, odio putant mentitum ea ius. Vix nostro deserunt explicari eu.</p> </article> </div> <ul> <li><a href="#">Link1</a></li> <li><a href="#">Link2</a></li> <li><a href="#">Link3</a></li> <li><a href="#">Link4</a></li> </ul><span></span> <a href="#">Some link</a> <script src="main.js"></script> </body> </html> 

      You line

       let li = document.getElementById('ul'); 

      ask to give you a page element with id='ul' . But you do not have such an element on the page. Change <ul> to <ul id="ul"> and everything will work