admin管理员组文章数量:1389762
How can I set the innner html of a span
element in dom that is under li>a>
?
<li class="first">
<a>
<span aria-hidden="true">1</span>
</a>
</li>
I have tried something like this, but nothing was written:
element[i].childNodes[1].children.innerHTML = number;
How can I set the innner html of a span
element in dom that is under li>a>
?
<li class="first">
<a>
<span aria-hidden="true">1</span>
</a>
</li>
I have tried something like this, but nothing was written:
element[i].childNodes[1].children.innerHTML = number;
Share
Improve this question
asked Apr 12, 2017 at 10:57
LeffLeff
1,44031 gold badges111 silver badges226 bronze badges
4
- 1 indexes start at 0, and children is a collection – Sebas Commented Apr 12, 2017 at 10:57
- @Sebas — Text nodes appear in the list of child nodes – Quentin Commented Apr 12, 2017 at 10:58
-
What is
element
? Why not usefirstElementChild
? Why not usequerySelector
? – evolutionxbox Commented Apr 12, 2017 at 10:58 - @Quentin I stand corrected – Sebas Commented Apr 12, 2017 at 10:59
2 Answers
Reset to default 5children
is an HTMLCollection. innerHTML
only applies to HTML elements. You need to find the HTML element in the children before using innerHTML
.
It doesn't make a lot of sense to mix the use of childNodes
and children
. Use the former for more patibility across browsers, use the latter for a simpler approach that lets you consider only element nodes.
var li = document.querySelector("li");
var number = 13;
li.children[0].children[0].innerHTML = number;
<ul>
<li class="first">
<a>
<span aria-hidden="true">1</span>
</a>
</li>
</ul>
Alternatively, you could just use querySelector
:
var li = document.querySelector("li");
var number = 13;
li.querySelector("a").innerHTML = number;
<ul>
<li class="first">
<a>
<span aria-hidden="true">1</span>
</a>
</li>
</ul>
I remend using jQuery (http://jquery.) and then use can simply do
$('li > a > span').html('THE INNER HTML HERE');
or
$('li > a').find('span').html('THE INNER HTML HERE');
you can use .first()
to the result of find() function to get the first element
本文标签: Javascriptget child of childStack Overflow
版权声明:本文标题:Javascript - get child of child - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744690942a2619990.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论