Skip to content Skip to sidebar Skip to footer

Multiple Selectors With Document.queryselectorall

Hot to get multiple selectors values using document.querySelectorAll? I need to get URL inside selectors.

Solution 1:

The syntax for assigning class or any atrribute to elements in Html is this:

<div class="myClass">

You don't need a . to assign a class name to an element but need it in case of accessing like you did above.

Solution 2:

You have a few issues in your HTML:

  1. the class should be changed from: <div class".myClass"> to <div class="myClass">

  2. you forgot to close the <div> with </div>

  3. if you use document.querySelectorAll() you can use forEach() to iterate over all the elements.

var x = document.querySelectorAll(".myClass");
x.forEach(function(element, index){
    console.log(index + ': -> ' + element.children[0].href);
});
<divclass="myClass"><ahref="link1.html"></a></div><divclass="myClass"><ahref="link2.html"></a></div><divclass="myClass"><ahref="link3.html"></a></div>

if you don't want to use forEach() (you still need to change point 1 and 2) the code will look like so:

var x = document.querySelectorAll(".myClass");

for(var i=0; i < x.length; i++){
    console.log(i + ': -> ' + x[i].children[0].href);
}
<divclass="myClass"><ahref="link1.html"></a></div><divclass="myClass"><ahref="link2.html"></a></div><divclass="myClass"><ahref="link3.html"></a></div>

Append string to url:

var x = document.querySelectorAll(".myClass");

for(var i=0; i < x.length; i++){
    x[i].children[0].href = x[i].children[0].href + '&item1=yes';
    console.log(i + ': -> ' + x[i].children[0].href);
}
<divclass="myClass"><ahref="link1.html"></a></div><divclass="myClass"><ahref="link2.html"></a></div><divclass="myClass"><ahref="link3.html"></a></div>

Solution 3:

  1. Use class="someClass" syntax (class="myClass").
  2. The childNodes index starts from 0. Use x[i].childNodes[0].href
  3. The div elements don't have corresponding closing tags.

Post a Comment for "Multiple Selectors With Document.queryselectorall"