我想获取许多具有相同ID的div的HTML内容,这是我的代码:
<div id="my_div">This is content I</div>
<div id="my_div">This is content J</div>
<div id="my_div">This is content P</div>
<div id="my_div">This is content Z</div>
这是我的jQuery代码:
document.getElementById('my_div').innerHTML;
但它只给了我一个div的内容。例如This is content I
。这就是我真正想要的This is content IThis is content JThis is content PThis is content Z
。请问我该如何运行我的代码?
答案 0 :(得分:1)
开始于:
<div class="my_div">This is content I</div>
<div class="my_div">This is content J</div>
<div class="my_div">This is content P</div>
<div class="my_div">This is content Z</div>
然后在.my_div的选择器上使用jQuery .each。请参阅Dhara Parmar的答案
$(".my_div").each(function( index ) {
console.log( index + ": " + $( this ).html() );
});
将显示结果,然后最终在循环中连接。
答案 1 :(得分:1)
为所有div添加相同的类:试试这个:
<div class="my_div">This is content I</div>
<div class="my_div">This is content J</div>
<div class="my_div">This is content P</div>
<div class="my_div">This is content Z</div>
var str ="";
$(".my_div").each(function() {
str = str + $(this).html() + " ";
})
alert(str)
答案 2 :(得分:0)
将您的html更改为使用class
而不是id
:
<div class="my_div">This is content I</div>
<div class="my_div">This is content J</div>
<div class="my_div">This is content P</div>
<div class="my_div">This is content Z</div>
循环遍历其值以获取其中的每一个:
function showDivValues(){
var length = document.getElementsByClassName('my_div').length;
for(var i = 0; i < length; i++){
console.log(document.getElementsByClassName('my_div')[i].innerHTML);
}
}