gpt4 book ai didi

javascript - setAttribute 不是函数

转载 作者:行者123 更新时间:2023-11-30 10:57:20 29 4
gpt4 key购买 nike

这是一些 HTML:

<ul>
<li>lorem</li>
<li>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Eaque magnam expedita aspernatur suscipit ea ad nisi corporis sequi labore consequatur odit, impedit quia quisquam inventore, recusandae similique esse excepturi distinctio.</li>
<li>Susan</li>
<li>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad vitae consequatur vel nostrum? Sunt, quas iure libero aut laborum facere unde quidem dolorem dicta, eaque, eveniet dolore harum iste deleniti.</li>
</ul>

和 JavaScript:

var text = document.getElementsByTagName('ul')[0];
var firstItem = text.firstChild;
var lastItem = text.lastChild;
firstItem.setAttribute('class', 'complete');

浏览器显示这个错误:

firstItem.setAttribute is not a function

最佳答案

您需要执行 firstItem.setAttribute('class', 'complete'); 因为 firstItem 中已经有一个元素。您还需要将 firstChildlastChild 更改为 firstElementChildlastElementChild 以便您可以使用 setAttribute () 方法:

var text = document.getElementsByTagName('ul')[0];

var firstItem = text.firstElementChild;

var lastItem = text.lastElementChild;
firstItem.setAttribute('class', 'complete');
lastItem.setAttribute('class', 'done');
.complete{
color: red;
}
.done {
color: blue;
}
<ul>
<li>lorem</li>
<li>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Eaque magnam expedita aspernatur suscipit ea ad nisi corporis sequi labore consequatur odit, impedit quia quisquam inventore, recusandae similique esse excepturi distinctio.</li>
<li>Susan</li>
<li>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad vitae consequatur vel nostrum? Sunt, quas iure libero aut laborum facere unde quidem dolorem dicta, eaque, eveniet dolore harum iste deleniti.</li>
</ul>

关于javascript - setAttribute 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59486894/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com