[英]jQuery get divs html from inside div
I have the following html: 我有以下html:
<div id="parent">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
I'm trying to get all the divs html from within the div
with id="parent"
. 我正在尝试使用
id="parent"
从div
获取所有div html。 After that build an array and push each html to it. 之后,建立一个数组并将每个html推入其中。
Basically I need to get this: 基本上我需要得到这个:
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
rather then this: 而不是这样:
1
2
3
4
And the jQuery code: 和jQuery代码:
var val = [];
$.each($('#parent'), function (i, left) {
$('div', left).each(function () {
var data = $(this).html();
val.push(data);
});
});
alert(JSON.stringify(val));
You could use the .map()
method , which will return an array of the children div
elements. 您可以使用
.map()
方法 ,该方法将返回子div
元素的数组。
var divs = $('#parent div').map(function () {
return this;
}).get();
You don't need to use jQuery for this, though. 不过,您无需为此使用jQuery。 Here is a plain JS option which returns the same results:
这是一个简单的JS选项,它返回相同的结果:
var divs = Array.prototype.map.call(document.querySelectorAll('#parent div'), function (el) {
return el;
});
count=$('#parent > div').length;
for(i=0;i<count;i++){
console.log($('#parent > div')[i].outerHTML);
}
https://jsfiddle.net/uabL649m/2/ https://jsfiddle.net/uabL649m/2/
try outerHTML , like below. 尝试externalHTML ,如下所示。 Demo@ fiddle
演示@ 小提琴
var arr = [];
$("#parent > div").each(function() {
arr.push(this.outerHTML);
});
console.log ( JSON.stringify(arr ) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.