How to get the item id correctly?

I try to get an element that id is a "div", but I get a TypeofError in firefox, what's the reason?

<script type="text/javascript">
window.onload = function (){
    var oParent = document.getElementsByTagName('div')[0];
    console.log(oParent);
    var arr = oParent.getElementById('div');
    console.log(arr);
    }
</script>
<div class="test">
<div></div>
<div></div>
<div id="div"></div>
<div></div>

+4
source share
3 answers

You must replace

var arr = oParent.getElementById('div');

with

var arr = document.getElementById('div');

This is because getElementById- this is a method document, not divs.

+7
source

This does not work because you are using the "getElementById" method from the oParent object. But this method is available from the document object.

var arr = document.getElementById('div');
+1
source

. , :

<script type="text/javascript">
    window.onload = function (){
      var oParent = document.getElementsByTagName('div');// this return array
      console.log(oParent);
      // loop through array and find your desired div
      for (var j=0; j<oParent.length; j++) 
      {
        if(oParent[j].id == 'div')
        {
          console.log(oParent);// here is your div
        }
      } 
    }
</script>


div id=div, , getElementById.

.

<script type="text/javascript">
    window.onload = function (){
      var oParent = document.getElementById('div');// this return div with id='div'
      console.log(oParent);

    }
</script>
0

Source: https://habr.com/ru/post/1539415/


All Articles