Lew*_*ite 2 javascript class href getelementsbyclassname
我正在尝试处理一个页面以查找某个 div 类中的 href 值。请记住,我没有使用<a>
.
这是我所拥有的:
var domains = document.getElementsByClassName('r');
for(var i = 0; i < domains.length; i++){
var hello = document.getElementsByClassName('r')[i].innerHTML;
alert(hello);
}
Run Code Online (Sandbox Code Playgroud)
这很好用,并且会“提醒”班级中的内容。(我知道这在 IE 中没有得到很好的支持,但这很好)。
我收到如下警报:
<a href="http://stackoverflow.com/questions/887307/getting-href-value-of-from-a-tag" onmousedown="return rwt(this,'','','','1','AFQjCNGsxCA6nMXughTW44nSEa94KtbEaQ','','0CC8QFjAA','','',event)"> <em>javascript</em> - <em>getting href</em> value of from <a> tag - Stack Overflow</a>
Run Code Online (Sandbox Code Playgroud)
在 href 中获取值的最佳方法是什么?
HTML 是这样的:
<h3 class="r"><a onmousedown="return rwt(this,'','','','1','AFQjCNFgNBuo2EfLPoNBi3hGgbuTeLwODw','','0CC8QFjAA','','',event)" href="http://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&ved=0CC8QFjAA&url=http%3A%2F%2Fwww.w3schools.com%2Fjsref%2Fprop_html_innerhtml.asp&ei=LacjUo4lw9m0BpLVgYAK&usg=AFQjCNFgNBuo2EfLPoNBi3hGgbuTeLwODw&bvm=bv.51495398,d.Yms"> … </a></h3>
Run Code Online (Sandbox Code Playgroud)
使用Element.attributes
代替Element.innerHTML
。对于 HTML,您还需要使用内部循环来获取元素的<a>
子.r
元素:
var domains = document.getElementsByClassName('r');
for(var i = 0; i < domains.length; i++){
var anchors = domains.getElementsByTagName('a');
for (var j = 0; j < anchors.length; j++) {
alert(anchors[j].attributes.href);
}
}
Run Code Online (Sandbox Code Playgroud)
或者您可以切换到Element.querySelectorAll()
更好的查询 API:
var anchors = document.querySelectorAll('.r > a');
for (var i = 0; i < anchors.length; i++) {
alert(anchors[i].attributes.href);
}
Run Code Online (Sandbox Code Playgroud)
请注意,我重用了该domains
变量,因为没有理由在每次循环迭代时都重新查询 DOM。