CSS personal-selectors do not seem to work with the querySelector method

Asked

Viewed 26 times

2

Basically, I need to access the href of the last tag anchovy and change their value.

const modHref = document.querySelector('.menu a:last-child');
modHref.setAttribute('href', 'ricardo.com');
console.log(modHref);
<nav class="menu">

    <ul>
        <li><a href="#animais">Animais</a></li>
        <li><a href="#faq">FAQ</a></li>
        <li><a href="#contato">Contato</a></li>
        <li><a href="#">Dev →</a></li>
    </ul>

</nav>

But apparently, the querySelector method simply ignores the pseudo-selector selects it directly from the first anchovy. Is this an expected behavior or am I ignoring something?

1 answer

3


Your problem is that you mounted the selector the wrong way.

Should be ('.menu ul li:last-child a') pseudo-selector na li

Notice that you don’t have <a> brother of <a> then all are first and last. To fix you have to select the last <li> and so the <a> within it

const modHref = document.querySelector('.menu ul li:last-child a');
modHref.setAttribute('href', 'ricardo.com');
console.log(modHref);
<nav class="menu">

  <ul>
    <li><a href="#animais">Animais</a></li>
    <li><a href="#faq">FAQ</a></li>
    <li><a href="#contato">Contato</a></li>
    <li><a href="#">Dev →</a></li>
  </ul>

</nav>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.