Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get id of the element correctly?

Tags:

javascript

I try to get element which id is "div", but I get an 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>

like image 913
Todd Mark Avatar asked Feb 13 '23 01:02

Todd Mark


2 Answers

You should replace

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

with

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

This because getElementById is a method of document and not of the divs.

like image 57
Matteo Tassinari Avatar answered Feb 15 '23 14:02

Matteo Tassinari


It doesn't work because you use the method "getElementById" from oParent object. But this method is available from document object.

var arr = document.getElementById('div');
like image 36
Frédéric GRATI Avatar answered Feb 15 '23 13:02

Frédéric GRATI