就像标题所说的那样,我正在寻找一种快速的方法来编写关于jQuery代码$('.div a')
的" plain" JavaScript的。我知道我们可以getElementsByClassName
找到.div
,但如何找到它包含的链接呢?
答案 0 :(得分:9)
答案 1 :(得分:1)
不使用querySelector
或querySelectorAll
document.getElementsByClassName('div')[0].getElementsByTagName('a')[0].style.color = 'red';

<div class="div">
<a href="javascript:void(0)">Link 1</a>
<a href="javascript:void(0)">Link 2</a>
<a href="javascript:void(0)">Link 3</a>
</div>
&#13;
要选择所有链接,
var links = document.getElementsByClassName('div')[0].getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].style.color = 'red';
}
&#13;
<div class="div">
<a href="javascript:void(0)">Link 1</a>
<a href="javascript:void(0)">Link 2</a>
<a href="javascript:void(0)">Link 3</a>
</div>
&#13;