Can you please let me know how to console log all href
of <a>
tags in a div #res
using pure JavaScript. I have a div like
<div id="res">
<a href="ssssssss-1.html">Data</a>
<a href="ssssssss-2.html">Data</a>
<a href="ssssssss-3.html">Data</a>
<a href="ssssssss-4.html">Data</a>
<a href="ssssssss-5.html">Data</a>
</div>
Can you please let me know how to console log all href
of <a>
tags in a div #res
using pure JavaScript. I have a div like
<div id="res">
<a href="ssssssss-1.html">Data</a>
<a href="ssssssss-2.html">Data</a>
<a href="ssssssss-3.html">Data</a>
<a href="ssssssss-4.html">Data</a>
<a href="ssssssss-5.html">Data</a>
</div>
Share
Improve this question
asked Mar 4, 2016 at 21:40
BehseiniBehseini
6,33823 gold badges86 silver badges139 bronze badges
2 Answers
Reset to default 7
var links = document.querySelectorAll('#res a');
for(var i = 0; i < links.length; i++){
console.log(links[i].href);
};
<div id="res">
<a href="ssssssss-1.html">Data</a>
<a href="ssssssss-2.html">Data</a>
<a href="ssssssss-3.html">Data</a>
<a href="ssssssss-4.html">Data</a>
<a href="ssssssss-5.html">Data</a>
</div>
Try to use querySelectorAll()
to grab the required elements, iterate over it and print its href
attribute by using .getAttribute(attributeName)
function,
Array.from(document.querySelectorAll("#res > a")).forEach(function(itm){
console.log(itm.getAttribute('href'));
});