jQuery:获取元素的父级
考虑以下HTML:jQuery:获取元素的父级,jquery,dom,Jquery,Dom,考虑以下HTML: <div class="votingButton"> <i class="icon-chevron-up"></i> </div> 上面的代码给了我,我也试过这些案例: $(this).closest('.votingButton').html() $(this).parents().html() $(this).parents('.votingButton').html() 但仍然得到 有什么想法吗?当然有。
<div class="votingButton">
<i class="icon-chevron-up"></i>
</div>
上面的代码给了我
,我也试过这些案例:
$(this).closest('.votingButton').html()
$(this).parents().html()
$(this).parents('.votingButton').html()
但仍然得到
有什么想法吗?当然有。您正在使用
.parent().html()
。.icon chevron up
元素父元素的HTML为:
<i class="icon-chevron-up"></i>
div class=“votingButton”
的.html是
<i class="icon-chevron-up"></i>
试试这个(更新并测试):
$(function () {
$('.icon-chevron-up').on('click', function () {
alert($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
});
});
$(函数(){
$('.icon-chevron-up')。在('click',函数(){
警报($(this.parent().wrap(“”).parent().html());
$(this.parent().unwrap();
});
});
这将为您提供父容器(及其子容器)的html代码。父容器的html是
。。。我不理解你的问题。它在parent
中为html返回正确的值:)
我想要所有的HTML作为结果,包括父元素。这将返回未定义的,因为jQuery返回的parent()
对象没有outerHTML
属性。您需要使用parent()[0].outerHTML
。关于如何获取元素的外部HTML的问题已经被问了很多次,并且在这里已经有了一个高投票率的答案:-这个答案还说明了为什么不应该使用outerHTML
属性。
<i class="icon-chevron-up"></i>
<span>Hello, world!</span>
<i class="icon-chevron-up"></i>
$(function () {
$('.icon-chevron-up').on('click', function () {
$(this).parent().html("Removing the icon since that's the actual content of the parents div");
});
});
$(function () {
$('.icon-chevron-up').on('click', function () {
alert($(this).parent().wrap('<p/>').parent().html());
$(this).parent().unwrap();
});
});