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>
We can use document. querySelector on to select a div and then select an element within it with the given class after that. We just call querySelector on the element with the ID mydiv to select items inside that div. Therefore, innerDiv is the div with the class myclass .
getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
The <div> tag defines a division or a section in an HTML document. The <div> tag is used as a container for HTML elements - which is then styled with CSS or manipulated with JavaScript. The <div> tag is easily styled by using the class or id attribute. Any sort of content can be put inside the <div> tag!
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");
var x = document.getElementById("parent").querySelector("#child"); // don't forget a #
or
var x = document.querySelector("#parent").querySelector("#child");
or
var x = document.querySelector("#parent #child");
or
var x = document.querySelector("#parent"); var y = x.querySelector("#child");
eg.
var x = document.querySelector("#div1").querySelector("#edit2");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With