开发者

jQuery: A shortcut to create a div container after a cue word

I'm creating a shortcut for a blog theme where I want to generate a div container around elements after using a cue word. For example, my blog entry would like this:

<div class="entry">

<p>First Paragraph</p>

<p>[box]</p>

<p>Second Paragraph</p>

<p>Third Paragraph</p>

</div> <!-- .entry -->

I'm hoping with some jQuery magic it could turn into this:

<div class="entry">

<p>First Paragraph</p>

<div class="box">

<p>Second Paragraph</p>

<p>Third Paragraph</p>

</div> <!-- .box -->

</div> <!-- .entry -->

One more rule: When I create a container box, I know I will always generate it before the closing div.entry. I'm hoping this restriction will make it easier to write the rules for jQuery. For example, I will never want the markup to look like this where there is content proceeding the div.box container:

<!-- I will never mark it up this way --开发者_运维问答>

<div class="entry">

<p>First Paragraph</p>

<div class="box">

<p>Second Paragraph</p>

</div> <!-- .box -->

<p>Third paragraph</p>

</div> <!-- .entry -->


I think your best bet is the jQuery :contains() selector. With it you could do things like this (note: it matches any paragraph that has [box] in its HTML and maybe you need to escape the brackets):

$("p:contains('[box]')").wrap($('<div>').addClass('box'));

And btw. accepting answers and proving that you already put effort in your problem will make it much more likely to get a helpful reply.


It will be something like this:

$("div.entry").append(
  $("<div>").addClass("box").append("p:contains([box])+*");
);
$("p:contains([box])").remove();


See an example of the following here.

You can find the index() of the [box] paragraph and then wrapAll() the <p> after using :gt() to get all the parapgraphs following it:

var boxAt;

$('p').each(function(){
    var $t = $(this);
    if ($t.html() === '[box]') {
        boxAt = $t.index();
        $t.remove();
    }
});

$('p:gt(' + (boxAt - 1) + ')').wrapAll('<div class="box">');


Thanks everyone for your help! It helped me also come up with another strategy that worked for me as well:

$('.entry p:contains([box])').each( function() {
    $(this).prevAll().wrapAll('<div class="lefty">');
});

$('.entry p:contains([box])').each( function() {
    $(this).nextAll().wrapAll('<div class="righty">');
});
$("p:contains([box])").remove();

What this does is create two separate boxes: 1. elements preceding [box], 2. elements proceeding [box]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜