在开发过程中,取得某个节点下的html代码,通常使用jQuery.html();
<section class="content-header">
<h1>
Dashboard <small>Control panel</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active">Dashboard</li>
</ol>
</section>
<script>
console.log($('.breadcrumb').html());
console.log($('.breadcrumb').prop('outerHTML'));
console.log($('.breadcrumb').prop('innerHTML'));
</script>
这里的html()只能取得ol.breadcrumb下的li结点,并不包括<ol>本身。
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active">Dashboard</li>
如果想取得<ol>节点,想通过使用parent().html()也是行不通的,因为<ol>还有个兄弟节点<h1>,所以parent().html()方法将会返回<h1>和<ol>。
<h1>
Dashboard <small>Control panel</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active">Dashboard</li>
</ol>
这时可使用jQuery.prop(‘outerHTML’)方法。
outerHTML是原生JS DOM的内置属性(property),用来获取当前节点的html代码(包含当前节点),所以用jQuery的prop()能拿到。
不能用jQuery.attr(‘outerHMTL’),,会返回undefined。
相应的原生JS DOM里还有innterHTML属性,使用jQuery.prop(‘innerHTML’)时,其效果和jQuery.html()相同,所以还是用html()好了,毕竟能少敲几个代码。