简体   繁体   中英

How to remove all elements except for one, maintaing the same CSS path to it?

I need to extract a single element (and all its contents) from a page, but still maintaining the same CSS tree that points to it.

To explain, let's say I have the following DOM:

<div>1
    <div>2</div>
    <div>3
        <div>4
            <div>5</div>
        </div>6
        <div>7
            <div>8
                <div>9</div>
            </div>
        </div>
        <div>10
            <div>
                <div>content</div>
            </div>
        </div>
    </div>
</div>

I am only interested in the element containing content , ie I need to transform the DOM in:

<div>
    <div></div>
    <div>
        <div></div>
        <div></div>
        <div>
            <div>
                <div>content</div>
            </div>
        </div>
    </div>
</div>

(the path to content should still be the same)

I am trying something like in this jsfiddle :

$("#want").siblings().html("");
$("#want").parents().siblings().html("");

which does not seem to be enough.

Suggestions?

EDIT: generalised the example, there can be any element instead of divs.

Maybe something like this:

var classForKeepings = 'keepThisItem';
var $elem = $('#want'); // give start element
$elem.addClass(classForKeepings); // give a class to make it stay

while( $elem.parent().length!==0 ){ // while the element has a parent
    $elem = $elem.parent(); // shift $elem to the parent
    $elem.addClass(classForKeepings ); // and add a class to make it stay
}

$('#startElement *:not(.'+classForKeepings+')').remove(); // remove all elements not tagged with the class
$('.'+classForKeepings ).removeClass(classForKeepings); // Cleanup afterwards

I used remove, since you dont need them. If you do need those, you can change it to .html('')

Use this sintax

$(function(){
   $("div:not(#want)").contents().filter(function() {
    return this.nodeType == 3; //Node.TEXT_NODE
   }).remove();     
});

Hope it helps.

This seems to be working.. too bad I need it to work with Cheerio but it seems there is no contents() .. guess I will have to use jsdom instead.. if I cannot find another solution..

$("#want").siblings().html("");
$("#want").parents().siblings().html("");
var want = $("#want").clone();
$("*").contents().filter(function() {
    return this.nodeType == 3; //Node.TEXT_NODE
 }).remove();
$("#want").replaceWith(want);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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