0

If I have a nested list like this:

<div class="nav">
    <ul>
        <li><a href="#number-one">Number 1</a></li>
        <li><a href="#number-two">Number 2</a></li>
        <ul>
            <li><a href="#number-three">Number 3</a></li>
            <li><a href="#number-four">Number 4</a></li>
        </ul>
        <li><a href="#number-five">Number 5</a></li>
    </ul>
</div>

I want to be able to get the href values from every one of these links using querySelector.

Something like this only returns the links in the top level :

const getNav = document.querySelector('.nav li');

How can I get all of the href values from every link in a nested list?

DumbMathBoy
  • 117
  • 2
  • 9
  • 1
    I think it should get them all. If not, I'll delete this comment. Just make sure you use `document.querySelectorAll()` if you want to select multiple elements – IT goldman Jul 11 '22 at 18:46
  • Something like `[...document.querySelectorAll('.nav li>a')].map(dom => dom.href);` ? – nick zoum Jul 11 '22 at 18:46

3 Answers3

1

In one line with querySelectorAll & map :

[...document.querySelectorAll('.nav li a')].map(({href})=>href)

Gives result:

['https://stackoverflow.com/questions/72943233/javas…ng-queryselector-on-multi-nested-lists#number-one', 'https://stackoverflow.com/questions/72943233/javas…ng-queryselector-on-multi-nested-lists#number-two', 'https://stackoverflow.com/questions/72943233/javas…-queryselector-on-multi-nested-lists#number-three', 'https://stackoverflow.com/questions/72943233/javas…g-queryselector-on-multi-nested-lists#number-four', 'https://stackoverflow.com/questions/72943233/javas…g-queryselector-on-multi-nested-lists#number-five']

live example

console.log([...document.querySelectorAll('.nav li a')].map(({href})=>href))
<div class="nav">
    <ul>
        <li><a href="#number-one">Number 1</a></li>
        <li><a href="#number-two">Number 2</a></li>
        <ul>
            <li><a href="#number-three">Number 3</a></li>
            <li><a href="#number-four">Number 4</a></li>
        </ul>
        <li><a href="#number-five">Number 5</a></li>
    </ul>
</div>
XMehdi01
  • 5,538
  • 2
  • 10
  • 34
0

querySelector only returns one element, in this case you will get the first li element after the nav class. To get all li you can use: querySelectorAll - as it return an array matching your select options. MDN DOCS

To get an attribute you'll use: element.getAttribute('href')

MDN DOCS

Example:

let elements = document.querySelectorAll('.nav li a')
elements.forEach(el => { 
 // logic goes here 
 let href = el.getAttribute('href')
})
Tomas Caetano
  • 11
  • 1
  • 2
0

You can use this code to get every href values.

const getNav = document.querySelectorAll('.nav li a');
   
    getNav.forEach(element=>{
        console.log(element.getAttribute("href"))
    })

querySelectorAll gets all of the a elements that are in .nav li then by a foreach loop you'll be able to get all href values of them.

Atena Dadkhah
  • 623
  • 1
  • 5
  • 19