Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
105
rated 0 times [  110] [ 5]  / answers: 1 / hits: 64598  / 10 Years ago, mon, april 28, 2014, 12:00:00

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>

More From » html

 Answers
32

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('');
}();

[edit 2021] Seven years old, this answer. See this snippet for another approach.


[#71276] Friday, April 25, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gregoriocoya

Total Points: 549
Total Questions: 111
Total Answers: 104

Location: Saint Helena
Member since Mon, Jan 16, 2023
1 Year ago
;