PLazzo
PLazzo

Reputation: 169

multiple selectors with document.querySelectorAll

Hot to get multiple selectors values using document.querySelectorAll?

I need to get URL inside selectors.

<div class".myClass"><a href="link1.html"></a>
<div class".myClass"><a href="link2.html"></a>
<div class".myClass"><a href="link3.html"></a>

I'm trying to use the follow but it is not working:

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

for(var i = 0; i < x.length; i++) {
    console.log (x[i].childNodes[1].href);
}

Upvotes: 0

Views: 975

Answers (3)

caramba
caramba

Reputation: 22490

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);
});
<div class="myClass"><a href="link1.html"></a></div>
<div class="myClass"><a href="link2.html"></a></div>
<div class="myClass"><a href="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);
}
<div class="myClass"><a href="link1.html"></a></div>
<div class="myClass"><a href="link2.html"></a></div>
<div class="myClass"><a href="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);
}
<div class="myClass"><a href="link1.html"></a></div>
<div class="myClass"><a href="link2.html"></a></div>
<div class="myClass"><a href="link3.html"></a></div>

Upvotes: 1

Nirmal
Nirmal

Reputation: 569

  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.

Upvotes: 1

Rohit Agrawal
Rohit Agrawal

Reputation: 1521

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.

Upvotes: 2

Related Questions