取得标记名为< div>的孩子仅在javascript中
问题描述:
我有一个HTML:
<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>
我想在javascript变量中获得所有带有id为xyz的父元素的标签为div的孩子.
I want to get all the children with tags as "div" of the parent element with id = xyz in a javascript variable.
这样我的输出应该是:
"<div id = "a"> hello </div>
<div id = "b"> hello
<div id="b1">I m a grand child</div>
</div>
<div id = "c"> hello </div>"
答
您可以使用querySelectorAll
:
var childDivs = document.querySelectorAll('#xyz div')
将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('');
}();
如果您需要与旧版浏览器(ic IE< 8)兼容,请使用@ Cerbrus '方法来检索div,或使用垫片.
If you need compatibility for older browsers (i.c. IE<8) use @Cerbrus' method to retrieve the divs, or use a shim.
为避免重复列出(嵌套的)div,您可能要使用
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('');
}();
这是 jsfiddle