Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting Children HTML elements with JavaScript

<body>

 <nav>
    <ul>
      <li><a href="index.html">Portfolio</a></li>
      <li><a href="about.html">About</a></li>
      <li><a href="contact.html">Contact</a></li>
    </ul>
 </nav>

 <section>
    <ul>
       <li><a href="previous-page.html">Previous</a></li>
       <li><a href="next-page.html">Next</a></li>
    </ul>
 </section>

</body>

I want to select what is inside the <li> tags that are in the <nav> element and put them in a list, but not include the <li> tags that are in <section>.

I've tried this code, but it selects all the list elements on the entire page:

let list = document.selectElementsByTagName('li')

I can only use vanilla JS, not jQuery.

like image 451
James Hall Avatar asked Nov 27 '25 23:11

James Hall


1 Answers

It's actually getElementsByTagName...
But you could use .querySelectorAll() like:

let list = document.querySelectorAll('nav li')

Example:

let list  = document.querySelectorAll('nav li');
let list2 = document.querySelector('section ul'); // Use rather some ID man 

Array.from(list).forEach( (el) => list2.append(el.cloneNode(true)) );
section {
  background: #eee;
}
<nav>
  <ul>
    <li><a href="index.html">Portfolio</a></li>
    <li><a href="about.html">About</a></li>
    <li><a href="contact.html">Contact</a></li>
  </ul>
</nav>

<section>
  <ul>
    <li><a href="previous-page.html">Previous</a></li>
    <li><a href="next-page.html">Next</a></li>
  </ul>
</section>
like image 192
Roko C. Buljan Avatar answered Nov 29 '25 13:11

Roko C. Buljan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!