search

Home  >  Q&A  >  body text

javascript - js natively determines dom element type

The problem is this

var id=document.getElementById(ele);
var cls=document.getElementsByClassName(ele);
var tag=document.getElementsByTagName(ele)

Now we need to determine what type of ele it is and write it like this, that is,
For example, if I enter a label 'a', it means the label, #a means id, and .a means class to perform the corresponding operation

<body>
<p id="app">
  测试1
</p>
<p>测试2</p>
<span class="span">测试3</span>
<script>
  window.onload=function () {
    function getreg(ele) {
      var id=document.getElementById(ele);
      var cls=document.getElementsByClassName(ele);
      var tag=document.getElementsByTagName(ele)
      alert(cls.getAttributeNode('p'))
    }
    getreg('app')
  }
</script>
</body>

The code is like this
Because there may be at least one element in the page

给我你的怀抱给我你的怀抱2747 days ago626

reply all(1)I'll reply

  • phpcn_u1582

    phpcn_u15822017-05-18 10:49:59

    1. If you simply want to get the element, you can use

      document.querySelectorAll
      document.querySelector
      //无需校验类型
    2. You must use the original idea to determine the input type

      //没加校验
      function check(str){
        var res = "tag";
        if(str.indexOf(".") > -1){
          res = "class";
        }else 
        if(str.indexOf("#") > -1){
          res = "id";
        }
        return res
      }

    reply
    0
  • Cancelreply