Reputation: 169
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
Reputation: 22490
You have a few issues in your HTML:
the class should be changed from: <div class".myClass">
to <div class="myClass">
you forgot to close the <div>
with </div>
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
Reputation: 569
class="myClass"
). x[i].childNodes[0].href
Upvotes: 1
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