简体   繁体   English

获取父元素html以及子内容

[英]Get the parent element html along with child content

I'm trying to get the parent element html along with the child content. 我正在尝试获取父元素html和子内容。 The structure is something like below... 结构如下所示...

<form>
<div id="my-div">
<span>My Span</span>
</div>
</form>

In my condition I've only access to "my-div" object and with that I want to traverse to "form" and then get the entire content including the form html. 在我的情况下,我只能访问"my-div"对象,并且想要遍历"form" ,然后获取包括html表单在内的全部内容。 What I've been trying is 我一直在尝试的是

$('#my-div').parent().html() - which is actually giving content from . $('#my-div').parent().html() -实际上是提供的内容。 But what I want is from <form> 但是我想要的是来自<form>

Try like: 试试:

$("#my-div").closest("form")[0].outerHTML;

https://developer.mozilla.org/en-US/docs/Web/API/Element.outerHTML https://developer.mozilla.org/zh-CN/docs/Web/API/Element.outerHTML

Or using .prop() 或使用.prop()

$("#my-div").closest("form").prop("outerHTML");

The .closest("form") will get you the parent FORM Element no matter where you nest your children #my-div in the future. 无论将来将孩子嵌套在#my-div.closest("form")都会为您提供父FORM元素。

jsBin demo jsBin演示

$('#my-div').parent().prop('outerHTML')

While this can be achieved with jQuery, it's an unnecessary expense for the most part, since the jQuery object has to be parsed and then the DOM Node retrieved from the object (unless using prop() ), with plain JavaScript it's a little cheaper: 尽管这可以使用jQuery来实现,但是在大多数情况下这是不必要的开销,因为必须先解析jQuery对象,然后再从对象中检索DOM Node(除非使用prop() ),而使用普通JavaScript则要便宜一些:

var htmlString = document.getElementById('my-div').parentNode.outerHTML;

 var html = document.getElementById('my-div').parentNode.outerHTML; document.getElementById('htmlResult').textContent = html; 
 #htmlResult { white-space: pre-wrap; padding: 0.5em; color: #666; border: 1px solid #000; border-radius: 1em; } #htmlResult::before { content: 'Result: '; color: #aaa; display: block; } 
 <form> <div id="my-div"> <span>My Span</span> </div> </form> <div id="htmlResult"></div> 

References: 参考文献:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM