简体   繁体   English

通过getElementById将另一个元素定位

[英]target an element in another one by getElementById

I have two element like this: 我有两个这样的元素:

<div id="first">
    <div id="test"></div>
</div>


<div id="second">
    <div id="test"></div>
</div>

then i want to getElementbyId('test'), However I need 'test' in first div. 然后我想要getElementbyId('test'),但是我需要在第一个div中进行“ test”。 meanwhile this is an example and my div doesn't have pre-defined order. 同时,这是一个例子,我的DIV没有预先定义的顺序。

It isn't valid to have multiple elements with the same ID, so you can't. 具有相同ID的多个元素是无效的,因此您不能这样做。

You should use class="test" instead. 您应该改为使用class="test"

<div id="first">
    <div class="test"></div>
</div>


<div id="second">
    <div class="test"></div>
</div>

Then do this: 然后执行以下操作:

var t = document.getElementById("second").querySelector(".test");

Or just this: 或者只是这样:

var t = document.querySelector("#second .test");

This will support all modern browsers, including Internet Explorer 8. If you need support for IE 7 and lower, you would need a helper method to get the element by class. 这将支持所有现代浏览器,包括Internet Explorer8。如果需要对IE 7及更低版本的支持,则需要一个帮助器方法来按类获取元素。

user1689607's comment re multiple ID's withstanding, assuming your html shown above is verbatim (that is to say, you can identify the container divs with a class or id as you have) user1689607的注释具有多个ID,假设您上面显示的html是逐字记录的(也就是说,您可以根据需要标识具有类或ID的容器div)

This works fine, tested in chrome. 在chrome上测试,这可以正常工作。

function mClick()
{
    var mfirst, msecond;

    mfirst = document.getElementById('first');
    msecond = document.getElementById('second');

    alert(mfirst.querySelector('#test').innerHTML);
    alert(msecond.querySelector('#test').innerHTML);
}



<div id="first">
    <div id="test">test1</div>
</div>

<div id="second">
    <div id="test">test2</div>
</div>

<input onclick='mClick();' value='click' type='button'/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM