Home  >  Q&A  >  body text

javascript - The JS code is compiled successfully, but an error is reported on the console. What is the problem?

<ul class="ul"><li>red</li>
    <li>1</li>
    <li>1</li>
    <li>1</li>
</ul>
<ul class="ul ul-2"><li>red</li>
    <li>1</li>
    <li>1</li>
    <li>1</li>
</ul>
<script type="text/javascript">
    var ulArry = document.getElementsByClassName("ul");
    for (var i in ulArry) {
        ulArry[i].firstChild.style.color = "#FF0000";
    }
</script>


# The color of li has changed, but why does the console still report an error?

大家讲道理大家讲道理2663 days ago857

reply all(5)I'll reply

  • typecho

    typecho2017-07-05 11:00:11

    ulArry is a NodeList object. For in not only obtains two Dom nodes, but also length, item(), namedItem(). So when it reaches length, an error is reported.
    You can print out ulArry[i] in the loop and see

    reply
    0
  • 迷茫

    迷茫2017-07-05 11:00:11

    You can see why the error is reported by looking at the picture, but as for why there is a length in in, this i is worth waiting for the expert to answer

    reply
    0
  • 迷茫

    迷茫2017-07-05 11:00:11

    Put the code into $(function(){}) and try it

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-07-05 11:00:11

    for in will report an error but for will not. The second ul class is not just one, but two. It is recommended to getElementsByTagName

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-07-05 11:00:11

    Please make sure the document is loaded before proceeding

    reply
    0
  • Cancelreply