Selecting HTML elements for kids 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 tags <li>
that are in the element <nav>
and put them in the list, but not include the tags <li>
that are in <section>
.
I tried this code, but it selects all list items in the whole page:
let list = document.selectElementsByTagName('li')
I can only use vanilla JS, not jQuery.
+3
source to share
2 answers
Actually getElementsByTagName
...
But you can 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>
+4
source to share