getAttribute(),setAttribute()的方法使用以及区别。

1.getAttribute()方法返回指定属性名的属性值 接受一个参数。

注:通过对象获取属性,只能获取到原始属性;

    //ps: getAttribute()可以获取原始属性和自定义属性的值 而通过对象获取属性值只能获取原始属性的值 如下所示:

<a href="#" target="_blank" data-index="one">getAttribute </a>
    var a=document.getElementSByTagName('a')[0];
    console.log(a.getAttribute('target') //_blank
    console.log(a.target) //_blank
    console.log(a.dataIndex)//undefined

2. setAttribute()方法接受两个参数:要设置的特性名和值。如果特性已存在,将替换原有的值;

    //ps: 可以操作自定义属性与原始属性。

 a.setAttribute("id","Attr");

 3. removeAttribute()此方法会删除元素的属性,也会删除元素中的值。

a.removeAttribute("target")
以上是关于javascript中的dom特性所包含方法之一 ,若有错误请联系更正。希望与大家一起成长,虽然我只是一枚小小白。

猜你喜欢

转载自blog.csdn.net/Miss_GL/article/details/79646989