简体   繁体   中英

How to wrap in 2 elements with jQuery?

I want to make the following code:

<h2>TEXTz</h2>
<p>ARTICLE</p>


<h2>TEXTx</h2>
<p>ARTICLE</p>

Look like this:

<div class="highlight">
<h2>TEXTz</h2>
<p>ARTICLE</p>
</div>

<h2>TEXTx</h2>
<p>ARTICLE</p>

But I have to use: contains for find h2 text and add wrap before h2 and after p .

My failed code:

$.extend($.expr[':'],{containsExact: function(a,i,m){return $.trim(a.innerHTML.toLowerCase()) === m[3].toLowerCase();}});

var byItem = "TEXTz"

var ItemTitle = $("h2:containsExact(" + byItem +")").text();
var ItemDes = $("h2:containsExact(" + byItem +")").next("p").text();

$("h2:containsExact(" + byItem +")").html('<section class="highlightitem"><h2>' + ItemTitle + '</h2><p>' + ItemDes + '</p></div>');

http://jsfiddle.net/NDUzW/

The method .add() allows adding elements to a jquery object.

Then you can use .wrapAll() to wrape a set of elements in jQuery.

var $h2 = $("h2:containsExact(" + byItem +")");
if ($h2.length) {
    $h2.add( $h2.next('p') )
       .wrapAll( $('<div>').addClass('highlight') );
}

Working example on jsfiddle

Simply use the jQuery functions:

var byItem = "TEXTz"

    $("h2")
        .filter(
            function() {
                if ($(this).html() == byItem) {
                    return true;
                }
                return false;
           }
       )
       .next("p")
       .andSelf()
       .wrapAll($("<section>")
            .addClass("highlightitem")
       );

Example

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