Get children tagged as <div> in javascript only
I have HTML like:
<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 all children with tags to be like a "div" of the parent element with id = xyz in the javascript variable.
So my conclusion 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>"
+4
4 answers
You can use querySelectorAll:
var childDivs = document.querySelectorAll('#xyz div')
The method of converting divs to a string (for saving or for warning) can 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 (ic IE <8), use the @ Cerbrus ' method to extract a div or use a pad.
To avoid a double list of (nested) partitions, you can 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('');
}();
+6
#xyz div, div children:
var childDivs = document.getElementById('xyz').getElementsByTagName('div')
// ^ Get #xyz element; ^ find it `div` children.
Document.querySelectorAll , , IE 8/9 + queryselector.
+13
If you need only the coming xyz kids, 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]);
}
}
+5