最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to Console Log all Hyperlinks href in a Box Using Pure JavaScript - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

2 Answers 2

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'));
});

DEMO

发布评论

评论列表(0)

  1. 暂无评论