原生JS如何查询元素属性

在原生JavaScript中,查询元素属性的方法主要依赖于Element对象的属性访问器(.propertyName)或者getAttribute()方法。

使用属性访问器(.:
对于某些内置属性(如id, className, style等),你可以直接使用属性访问器来获取或设置它们。

var element = document.getElementById('myElement');  
var id = element.id; // 获取元素的id属性  
element.className = 'newClass'; // 设置元素的class属性

使用getAttribute()方法:
对于自定义属性或任何你希望以字符串形式获取的属性,可以使用getAttribute()方法。

var element = document.getElementById('myElement');  
var customAttr = element.getAttribute('data-custom-attribute'); // 获取自定义属性

使用setAttribute()方法:
你也可以使用setAttribute()方法来设置元素的属性。

var element = document.getElementById('myElement');  
element.setAttribute('data-custom-attribute', 'newValue'); // 设置自定义属性

使用removeAttribute()方法:
如果你想移除一个属性,可以使用removeAttribute()方法。

var element = document.getElementById('myElement');  
element.removeAttribute('data-custom-attribute'); // 移除自定义属性

对于布尔属性:
有些HTML属性是布尔属性(如checked, disabled, selected等),它们没有值,只关心是否存在。在JavaScript中,你可以直接访问这些属性来获取或设置它们的值。

var checkbox = document.querySelector('input[type="checkbox"]');  
var isChecked = checkbox.checked; // 获取checkbox的checked状态  
checkbox.checked = true; // 设置checkbox为选中状态

注意:使用属性访问器获取或设置的属性值通常是JavaScript类型的值(如数字、字符串、对象等),而getAttribute()setAttribute()方法总是以字符串形式处理属性值。 

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值