getElementById doesn't work on a node

血红的双手。 提交于 2019-12-10 16:09:05

问题


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>

回答1:


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




回答2:


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




回答3:


document.getElementById() won't work if the node was created on the fly and not yet attached into the main document dom.

For example with Ajax, not all nodes are attached at any given point. In this case, you'd either need to explicitly track a handle to each node (generally best for performance), or use something like this to look the objects back up:

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;
    }
}


来源:https://stackoverflow.com/questions/3902671/getelementbyid-doesnt-work-on-a-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!