views:

27

answers:

1

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>
+2  A: 

.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.

Nick Craver
So, despite getElementById is often described together with other DOM methods as appliable to any node, in fact it's appliable only to document. OK, thanks.
Ursus Russus