问题
I have a HTML as:
<div id="xyz">
<svg>......</svg>
<img>....</img>
<div id = "a"> hello </div>
<div id = "b"> hello
<div id="b1">I m a grand child</div>
</div>
<div id = "c"> hello </div>
</div>
I want to get all the children with tags as "div" of the parent element with id = xyz in a javascript variable.
Such that my output should be:
"<div id = "a"> hello </div>
<div id = "b"> hello
<div id="b1">I m a grand child</div>
</div>
<div id = "c"> hello </div>"
回答1:
You can use querySelectorAll
:
var childDivs = document.querySelectorAll('#xyz div')
A method to transform the divs to a string (to store or to alert) could be:
var divsHtml = function () {
var divhtml = [],
i = -1,
divs = document.querySelectorAll('#xyz div');
while (i++ < divs.length) {
divs[i] && divhtml.push(divs[i].outerHTML);
}
return divhtml.join('');
}();
If you need compatibility for older browsers (i.c. IE<8) use @Cerbrus' method to retrieve the divs, or use a shim.
To avoid double listing of (nested) divs, you may want to use
var divsHtml = function () {
var divhtml = [],
i = -1,
divs = document.querySelector('#xyz').childNodes;
while (i++ < divs.length) {
divs[i] &&
/div/i.test(divs[i].tagName) &&
divhtml.push(divs[i].outerHTML);
/* ^ this can also be written as:
if(divs[i] && /div/i.test(divs[i].tagName) {
divhtml.push(divs[i].outerHTML)
}
*/
}
return divhtml.join('');
}();
Here's a jsfiddle
回答2:
You can simply get the #xyz
div first, then find all div
children:
var childDivs = document.getElementById('xyz').getElementsByTagName('div')
// ^ Get #xyz element; ^ find it's `div` children.
The advantage of this method over Document.querySelectorAll
is that these selectors work in pretty much every browser, as opposed to IE 8/9+ for the queryselector.
回答3:
If you want only the immediate children of xyz, you can call
var childrendivs = document.querySelectorAll('#xyz > div');
or calculate them yourself, if you use an older browser without document.querySelectorAll
-Support
var childrendivs = [],
children = document.getElementById('xyz').children;
for(var i = 0; i < children.length; i++){
if (children[i].tagName == "DIV") {
childrendivs.push(children[i]);
}
}
回答4:
Unless I misunderstood, this is exactly what getElementsByTagName does.
来源:https://stackoverflow.com/questions/23335405/get-children-with-tagname-as-div-only-in-javascript