开发者

IE getelementbyid for object in the document

开发者 https://www.devze.com 2023-01-09 13:36 出处:网络
I need to getElementById for an object which already exists in the document. In the example, I would like 开发者_如何学Goto get the element \"test\" which is sub of parentDiv1.

I need to getElementById for an object which already exists in the document.

In the example, I would like 开发者_如何学Goto get the element "test" which is sub of parentDiv1.

It works fine in FF but not with IE. Any tips?

Example:

<div id="parentDiv1">
    <ul id="test1">test</ul>
</div>
<div id="parentDiv2">
    <ul id="test2">test</ul>
</div>
<script>
    var prtDiv1 = document.getElementById("parentDiv1");
    var test1 = prtDiv1.getElementById("test1");
</script>


You shouldn't have more than one element with the same id in your document. Use a class. The easiest way for you to do what you want then would be to use jQuery and write $('#parentDiv1 ul.test') to select your element. Other than jQuery, you would need to implement getElementsByClassName in javascript in IE because afaik it still doesn't support it natively.

Edit: Make sure there aren't any "name" attributes that have the same value as the target id, and also that the js variable you're setting has a different name than the target id.


Calling getElementById on a node is non-standard... If you want to get the element with ID test1 (as it is its id, this one should be unique) and check that it is a child of element with ID parentDiv1 rather use this :

// get the node with ID `test1` in the document
var test1 = document.getElementById("test1"); 

// Check if it is a child of `parentDiv1`
var isChild = document.getElementById("parentDiv1").contains(test1); 

You can look at MDN doc about contains here.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号