getElementById doesn't work on a node

Ursus Russus picture Ursus Russus · Oct 11, 2010 · Viewed 15k times · Source

In this simple script i get the error "obj.parentNode.getElementById is not a function", and I have no idea, what is wrong.

<script type="text/javascript">

        function dosomething (obj) {
         sibling=obj.parentNode.getElementById("2");
         alert(sibling.getAttribute("attr"));
        }

</script>

<body>
 <div>
  <a id="1" onclick="dosomething(this)">1</a>
  <a id="2" attr="some attribute">2</a>
 </div>
</body>

Answer

Nick Craver picture Nick Craver · Oct 11, 2010

.getElementById() is on document, like this:

document.getElementById("2");

Since IDs are supposed to be unique, there's no need for a method that finds an element by ID relative to any other element (in this case, inside that parent). Also, they shouldn't start with a number if using HTML4, a numberic ID is valid in HTML5.