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 use firstElementChild? Why not use querySelector? – evolutionxbox Commented Apr 12, 2017 at 10:58
  • @Quentin I stand corrected – Sebas Commented Apr 12, 2017 at 10:59
Add a ment  | 

2 Answers 2

Reset to default 5

children 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