Select Child after using querySelectorAll

Asked

Viewed 75 times

2

I’m looking to change some attributes within the fields: ul > li. In case I change the.url and img.src, however I am using a for to change the fields is using in the mode artistSimimarChild[i] how can I access ul > li > a and ul > li > a > img ?

HTML:

<ul class="ui-artist-related">
    <li class="ui-artist-related__column ui-artist-related__artist"><a href="#"><img src="assets/images/profiles/katyperry.jpg" /></a></li>
    <li class="ui-artist-related__column ui-artist-related__artist"><a href="#"><img src="assets/images/profiles/kesha.jpg" /></a></li>
    <li class="ui-artist-related__column ui-artist-related__artist"><a href="#"><img src="assets/images/profiles/arianagrande.jpg" /></a></li>
</ul>

Javascript:

const artistSimilar = document.querySelector(".ui-artist-related"),
artistSimimarChild = document.querySelectorAll("li.ui-artist-related__artist"); 

The closest way I thought would be to do:

var 1 = document.querySelectorAll("li.ui-artist-related__artist > a")[i];
var 2 = document.querySelectorAll("li.ui-artist-related__artist > a > img")[i];

However I do not want to keep creating several var to select a specific field and in the end get a mess my code.

1 answer

1


For the specified html you can use the selector you have specified li.ui-artist-related__artist > a to get to the links. After each link gets to the image that is inside it using the property childNodes and acceding to the first that is the position 0:

const as = document.querySelectorAll("li.ui-artist-related__artist > a");

for (let a of as){
  let imagem = a.childNodes[0];
  console.log(a.getAttribute("href")," tem imagem ", imagem.getAttribute("src"));
}
<ul class="ui-artist-related">
  <li class="ui-artist-related__column ui-artist-related__artist">
    <a href="link1"><img src="assets/images/profiles/katyperry.jpg" /></a>
  </li>
  <li class="ui-artist-related__column ui-artist-related__artist">
    <a href="link2"><img src="assets/images/profiles/kesha.jpg" /></a>
  </li>
  <li class="ui-artist-related__column ui-artist-related__artist">
    <a href="link3"><img src="assets/images/profiles/arianagrande.jpg" /></a>
  </li>
</ul>

To change the attributes you can use the function setAttribute:

for (let i=0;i < as.length; ++i){ 
  as[i].setAttribute("href", "novolink"+i);
  as[i].childNodes[0].setAttribute("src", "novosource"+i);
}

Documentation:

Browser other questions tagged

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