如何获取子div的内容?

时间:2016-06-07 03:15:47

标签: javascript jquery

为什么这不起作用:

<div class="store" id="vframestore">
    <div>http://www.youtube.com/embed/_6DPBCOukLU?showinfo=0&modestbranding=1&fs=0&rel=0</div>
    <div>http://www.youtube.com/embed/ZMr0q4Jz_uM?showinfo=0&modestbranding=1&fs=0&rel=0</div>
</div>

JS

var a = $("#vframestore").children[0].html;
console.log(a);
  

错误:未捕获的TypeError:无法读取未定义的属性'html'

5 个答案:

答案 0 :(得分:0)

你可以这样做。

var a = $("#vframestore").children().first().html();

或者

var a = $("#vframestore div").eq(0).html();

答案 1 :(得分:0)

使用vanilla JS:

document.querySelector('#vframestore > DIV').innerHTML

答案 2 :(得分:0)

你能使用CSS选择器吗?

var a = $("#vframestore div:first-child").html();

答案 3 :(得分:0)

&#13;
&#13;
var parent = document.getElementById("vframestore");
var child = parent.children[0].innerHTML;
//alert(child);
console.log(child);
&#13;
<div class="store" id="vframestore">
  <div>http://www.youtube.com/embed/_6DPBCOukLU?showinfo=0&modestbranding=1&fs=0&rel=0</div>
  <div>http://www.youtube.com/embed/ZMr0q4Jz_uM?showinfo=0&modestbranding=1&fs=0&rel=1</div>
</div>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

使用jquery的eq()获取所需的子div,.html()获取子div内容。

Jquery's .eq()

Jquery's .html()

&#13;
&#13;
$(document).ready(function() {
  var childDiv1 = $('#vframestore div').eq(0).html();
  var childDiv2 = $('#vframestore div').eq(1).html();

  // alert child div contents
  alert(childDiv1);
  alert(childDiv2);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="store" id="vframestore">
  <div>http://www.youtube.com/embed/_6DPBCOukLU?showinfo=0&modestbranding=1&fs=0&rel=0</div>
  <div>http://www.youtube.com/embed/ZMr0q4Jz_uM?showinfo=0&modestbranding=1&fs=0&rel=0</div>
</div>
&#13;
&#13;
&#13;

相关问题