Select child after using querySelectorAll

2

I want to change some attributes within the fields: ul > li . In the case I will change the a.url and img.src, however I am using a for for changing the fields it is using in the artistSimimarChild [i] mode how can I access the 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 way I thought next 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];

But I do not want to be creating several var to select a specific field and in the end it will be a mess my code.

    
asked by anonymous 07.11.2017 / 00:46

1 answer

1

For the indicated html you can use the selector that indicated li.ui-artist-related__artist > a to reach the links. After each link arrives at the image that is inside it using the childNodes property and accessing the first one 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 setAttribute function:

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

Documentation:

07.11.2017 / 00:55