自定义html的attributes

本代码来自Coursera的Angular课程,欢迎大家去参加课程.我节选出精华的片段,写到自己博客上.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>HTML5 Custom Attributes</title>
  </head>
  <body>
    <h1>HTML5 Custom Attributes</h1>

    <div id="target" ng-app="myTestApp">
      <section>Section 1
        <article>Article 1</article>
      </section>
    </div>
    <script>
    // var elem = document.getElementById('target');
    // console.log(elem);
    //
    // console.log(elem.getAttribute('ng-app'));
    var elem2 = document.querySelector("[ng-app]");
    console.log(elem2);
    console.log(elem2.getAttribute('ng-app'));
    </script>
  </body>
</html>

自定义的attribute,html解释器在解释时会自动忽略,因此不会破坏html的运行.

Javascript自带了访问自定义attribute的函数,document.getAttribute(),这可以得到该attribute的值.

此外,还可以通过document.querySelector("[name]")获得有该attribute的dom树的分支.

原文地址:https://www.cnblogs.com/dagon/p/5898342.html