0

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);
}
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
PLazzo
  • 169
  • 2
  • 13

3 Answers3

2

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.

Rohit Agrawal
  • 1,496
  • 9
  • 20
1

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>
caramba
  • 21,963
  • 19
  • 86
  • 127
  • are you brazilian? How to append data into grabbed url? I tried to use `x[i].children[0].href) = x[i].children[0].href) + '&item1=yes'` but did not works. – PLazzo May 23 '18 at 12:14
  • @PLazzo no I'm not Brazilian. Have a look at the updated answer **append string to url** – caramba May 23 '18 at 12:33
1
  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.
Nirmal
  • 549
  • 1
  • 9
  • 24