gpt4 book ai didi

javascript - className 与 get/setAttribute 方法

转载 作者:太空宇宙 更新时间:2023-11-04 13:40:33 25 4
gpt4 key购买 nike

我遇到过两种获取属性值的方法:首先是:

document.getElementById("id").getAttribute("class");
document.getElementById("id").setAttribute("class", "newClass");

另一个:

document.getElementById("id").className;

两者都可用于设置和获取类值或任何其他值。是否存在更可取的特定情况?一个比另一个快吗?它们有何不同?为什么甚至有两种方法呢?

最佳答案

他们做不同的事情。 .getAttribute('name') 获取属性,而 .name 获取属性。

属性是元素创建时HTML代码中属性设置的初始值。该属性是当前值,自创建元素以来可能已更改。

对于某些属性,属性随属性而变化,但对于某些属性,属性和属性是单独的值:

window.onload = function(){

var el = document.getElementById("id");

console.log("Attribute: " + el.getAttribute("value"));
console.log("Property: " + el.value);

console.log('Changing property');
el.value = 'b';

console.log("Attribute: " + el.getAttribute("value"));
console.log("Property: " + el.value);

};
<input type="text" id="id" value="a"></div>

关于javascript - className 与 get/setAttribute 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33451050/

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