简体   繁体   English

使HTML达到子元素

[英]Get HTML up to child element

Is there a way to get an HTML string, or document-fragment of an element, up to a certain element? 有没有一种方法可以获取一个元素的HTML字符串或document-fragment ,直到一个特定元素?

For example, say I have the following HTML 例如,说我有以下HTML

<div id="blocks">
    <div class="block">
        <div>
            <ul>
                <li id="target">Some List Item</li>
                <li>Some Other List Item</li>
            </ul>
        </div>
    </div>
</div>

This is just an example, the HTML will actually be much more complicated and with more levels 这只是一个例子,HTML实际上会更加复杂并且层次更多

What I'd like to be able to do is something like: 我想要做的是这样的:

$(".block").html("#target")

And get a HTML string such as: 并获取一个HTML字符串,例如:

<div>
    <ul>
         <li id="target">Some List Item</li>
    </ul>
</div>

Notice how there's only one list item in the resulting HTML 请注意,结果HTML中只有一个列表项

I want to get all the HTML of the .block element, up to the #target element 我想获取.block元素的所有HTML,直至#target元素

Thanks! 谢谢!

//clone the original `.block` and get it's `#target`.
var cloned = $('#target').closest('.block').clone().find('#target');
var temp;
//go up the cloned parents and remove child that is not in the path of `#target`
while(true){
    temp = cloned.parent();
    var flag = false;
    temp.children().each(function(i, el){
        if(flag)
            $(el).remove();
        if($(el).is(cloned))
            flag = true;
    });
    if(cloned.is('.block')) break;
    cloned = temp;
}

After this the cloned.html() is what you need. 之后,您需要的是cloned.html() See the fiddle: http://jsfiddle.net/Fx5pU/ 参见小提琴: http : //jsfiddle.net/Fx5pU/

And note that this will not change the original HTML in contrast to some other solutions suggested here. 请注意,与此处建议的其他一些解决方案相比,这不会更改原始HTML。

Updated: 更新:

Clone the parents up to ".block" and remove the siblings of "#target". 克隆父母直到“ .block”,并删除“ #target”的兄弟姐妹。

var newBlock = $('#target').parents("div.block").clone();
newBlock.find('#target').siblings().remove();

Check out the working code at: 在以下位置查看工作代码:

JSFiddle 的jsfiddle

尝试这个

$('div.block').not('#target').remove()

演示

$('.block #target').nextAll().remove();

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

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