GetElementById does not work with node

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>
+3
source share
3 answers

.getElementById()located on document, for example:

document.getElementById("2");

Since identifiers must be unique , there is no need for a method that finds an element by identifier with respect to any other element (in this case, inside this parent). In addition, they should not start with a number when using HTML4; the numeric identifier is valid in HTML5.

+5
source

.getElementById(id) .querySelector('#' + id);

+2

document.getElementById() will not work if node was created on the fly and not yet attached to the main dom document.

For example, using Ajax, not all nodes are attached at any given point. In this case, you need to either explicitly track the descriptor for each node (usually best for performance), or use something like this to look at the objects:

function domGet( id , rootNode ) {
    if ( !id ) return null;

    if ( rootNode === undefined ) {

        // rel to doc base
        var o = document.getElementById( id );
        return o;

    } else {

        // rel to current node
        var nodes = [];
        nodes.push(rootNode);
        while ( nodes && nodes.length > 0 ) {
            var children = [];
            for ( var i = 0; i<nodes.length; i++ ) {
                var node = nodes[i];
                if ( node && node['id'] !== undefined ) {
                    if ( node.id == id ) {
                        return node; // found!
                    }
                }

                // else keep searching
                var childNodes = node.childNodes;
                if ( childNodes && childNodes.length > 0 ) {
                    for ( var j = 0 ; j < childNodes.length; j++ ) {
                        children.push( childNodes[j] );
                    }
                }
            }
            nodes = children;
        }

        // nothing found
        return null;
    }
}
+1
source

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


All Articles