Reputation: 643
I have HTML such as:
<div class="mt brn">
<a href="....">Country 1</a>
</div>
<div class="mt brn">
<a href="....">Capital 1</a>
</div>
<div class="mt brn">
<a href="....">Population</a>
</div>
I would like to know how to use Javascript (not jquery) to create an array:
[Country 1,Captial 1,Population]
I know the class of the DIV above each href will be set to "mt brn" - so I'd like it to ignore any a href text that isn't contained within the
Thanks in advance,
Mark
Upvotes: 0
Views: 117
Reputation: 26
You can try the following javascript code :
var divList = document.getElementsByClassName("brn");
var tab=[];
for (index = 0; index < divList.length; ++index) {
var text =divList[index].getElementsByTagName('a')[0].innerHTML;
tab.push(text);
}
Upvotes: 0
Reputation: 4480
Use document.querySelectorAll('.mt.brn a');
to get anchor tag inside the class .mt.brn
.Then loop throught the elements and use inneHTML to get the content.Or use textContent
to get the text
var elemts = document.querySelectorAll('.mt.brn a');
var textArray=[];
for(var i= 0;i< elemts.length;i++){
textArray.push(elemts[i].innerHTML )
}
console.log(textArray)
<div class="mt brn">
<a href="....">Country 1</a>
</div>
<div class="mt brn">
<a href="....">Capital 1</a>
</div>
<div class="mt brn">
<a href="....">Population</a>
</div>
Example using text Content:
var elemts = document.querySelectorAll('.mt.brn a');
var textArray=[];
for(var i= 0;i< elemts.length;i++){
textArray.push(elemts[i].textContent )
}
console.log(textArray)
<div class="mt brn">
<a href="....">Country 1</a>
</div>
<div class="mt brn">
<a href="....">Capital 1</a>
</div>
<div class="mt brn">
<a href="....">Population</a>
</div>
Upvotes: 5
Reputation: 7285
Use document.querySelectorAll
:
var anchorElements = document.querySelectorAll('.mt.brn > a');
var contents = [];
for (var i = 0; i < anchorElements.length; i++) {
contents.push(anchorElements[i].textContent);
}
console.log(contents);
<div class="mt brn">
<a href="....">Country 1</a>
</div>
<div class="mt brn">
<a href="....">Capital 1</a>
</div>
<div class="mt brn">
<a href="....">Population</a>
</div>
Upvotes: 0