我有一个可耻的问题,试图在没有jquery的情况下做事,我正在尝试将一个类添加到<i>
元素到<span>
,我知道这很容易用jquery做,但是我用Vanilla Javascript失败了:
<span id='my1'>
<i>...</i>
</span>
<span id='my2'>
<i>...</i>
</span>
<script type="text/javascript">
var i1 = document.querySelectorAll('#my1 i');
i1.className = 'test'
i1.textContent = 'yep'
var i2 = document.getElementById('my2').getElementsByTagName('i')
i2.className = 'test'
i2.textContent = 'yap'
i2..innerHTML = 'what?'
</script>
答案 0 :(得分:2)
.getElementsByTagName('i')
返回一个集合,因此您必须引用要修改的索引:
var i2 = document.getElementById('my2').getElementsByTagName('i')[0];
答案 1 :(得分:2)
您在这里有额外的.
:i2..innerHTHML
。除此之外,getElementsByTagName
返回一个数组,这是有道理的。你的数组有一个成员,所以你可以这样做:
i2[0].className = 'test'
i2[0].textContent = 'yap'
i2[0].innerHTML = 'what?'
答案 2 :(得分:0)
您需要解决几件事:
var i1 = document.querySelector('#my1 i'); //You want to return a single element, not all matches
i1.className = 'test';
i1.textContent = 'yep';
var i2 = document.getElementById('my2');
var i3 = i2.getElementsByTagName('i')[0]; //Added another var for readability, but you need to specify the first element of the returned array
i3.className = 'test'
i3.textContent = 'yap'
i3.innerHTML = 'what?'