2014-07-25 29 views
-2

假设我有以下的HTMLjQuery的返回内容的包装,而不是唯一的内容

<articles> 

    <article id="a1"> 
     <!-- Content of article with id="a1" --> 
    </article> 

    <article id="a2"> 
     <!-- Content of article with id="a2" --> 
    </article> 

    <article id="a3"> 
     <!-- Content of article with id="a3" --> 
    </article> 

</articles> 

使用jQuery,我做了以下

var x = $("#a2").html(); 

现在,变量x将contian :

<!-- Content of article with id="a2" --> 

但是,我喜欢有x包含:

<article id="a2"> 
    <!-- Content of article with id="a2" --> 
</article> 

我想:

var x = $("#a2").parent().html(); 

但返回的所有三篇文章,这不是我想要的。我只想要文章a2。我怎样才能做到这一点?

谢谢。

回答

1

尝试使用.outerHTML属性,

var x = $("#a2")[0].outerHTML; 
+0

为什么我必须使用索引[0]? – Greeso

+1

@Greeso由于'.outerHTML'是一个属性,属于普通javascript的元素对象。我们必须通过阅读索引0中的元素来获取它。 –

+2

outerHtml不是jQuery的属性,它是javascript。 var x = documentElementById('a2')。outerHTML; –