removeAttribute getAttribute setAttribute

1.removeAttribute() 方法删除指定的属性。

注:removeAttributeNode() 方法从元素中删除指定的属性节点。
简单的来讲,removeAttribute() 移除元素内的属性;

<style>
  .aaa{
    color:red;
  }
</style>
</head>
<body>
  <h1 class="aaa">Hello World</h1>
  <button onclick="myFunction()">点击</button>
  <script>
  function myFunction()
  {
  document.getElementsByTagName("h1")[0].removeAttribute("class");     //当点击的时候,h1的红色会变成黑色(默认黑色)应为移除了class这个属性
  }
  </script>
</body>

2.getAttribute() 方法通过名称获取属性的值。(属性不存在时返回null)

注:getAttributeNode() 方法从当前元素中通过名称获取属性节点。

<style>
    .aaa{
      color:red;
    }
</style>
</head>
<body>
  <h1 class="aaa">Hello World</h1>
  <button onclick="myFunction()">点击</button>
  <script>
    function myFunction()
    {
    var h1=document.getElementsByTagName("h1")[0];
    alert(h1.className);                    //两者都能有效果    aaa
    alert(h1.getAttribute("class"));      //             aaa
    }
  </script>
 </body>

获取 dom 节点数据请不要用其他方法,统一用getattribute,获取对象属性方括号是兼容性最广的,点号方便,但是低版本 ie 有兼容性问题。良好的编程习惯是减少bug的保证

3.setAttribute() 方法添加指定的属性,并为其赋指定的值。

*注意:如果这个指定的属性已存在,则仅设置/更改值。
和getAttribute一样,setAttribute只是用于元素节点
*

<body>
  <input value="OK">
  <p>点击按钮来设置按钮的 type 属性。</p>
  <button onclick="myFunction()">点击</button>
  <script>
    function myFunction()
    {
    document.getElementsByTagName("input")[0].setAttribute("type","button");  
    }
  </script>
</body>

点击前.png

点击后.png

Internet Explorer 8 以及更早的版本不支持此方法。

通过setAttribute对文档做出修改后,在通过浏览器的源代码查看时看到的仍然是改变前的属性值。这种“表里不一”的现象源自DOM的工作模式:先加载文档的静态内容,在动态刷新,动态刷新不影响文档的静态内容。

                                                      -DOM编程艺术

猜你喜欢

转载自www.cnblogs.com/baimeishaoxia/p/12187217.html