Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

javascript - Simple way to get element by id within a div tag?

Please forgive me if I repeat the question.

I have HTML that all elements inside a div tag has different id, suppose I have already get the reference to the div, is there any simple way to get the element by its id without iterate all elements with that div?

here is my sample html:

<div id="div1" >
    <input type="text" id="edit1" />
    <input type="text" id="edit2" />
</div>
<div id="div2" >
    <input type="text" id="edit1" />
    <input type="text" id="edit2" />
</div>
question from:https://stackoverflow.com/questions/7171483/simple-way-to-get-element-by-id-within-a-div-tag

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may try something like this.

Sample Markup.

<div id="div1" >
    <input type="text" id="edit1" />
    <input type="text" id="edit2" />
</div>
<div id="div2" >
    <input type="text" id="edit3" />
    <input type="text" id="edit4" />
</div>

JavaScript

function GetElementInsideContainer(containerID, childID) {
    var elm = {};
    var elms = document.getElementById(containerID).getElementsByTagName("*");
    for (var i = 0; i < elms.length; i++) {
        if (elms[i].id === childID) {
            elm = elms[i];
            break;
        }
    }
    return elm;
}

Demo: http://jsfiddle.net/naveen/H8j2A/

A better method as suggested by nnnnnn

function GetElementInsideContainer(containerID, childID) {
    var elm = document.getElementById(childID);
    var parent = elm ? elm.parentNode : {};
    return (parent.id && parent.id === containerID) ? elm : {};
}

Demo: http://jsfiddle.net/naveen/4JMgF/

Call it like

var e = GetElementInsideContainer("div1", "edit1");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...