javascript - js natively determines dom element type
给我你的怀抱
给我你的怀抱 2017-05-18 10:47:59
0
1
625

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

给我你的怀抱
给我你的怀抱

reply all(1)
phpcn_u1582
  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
    }
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template