wyc
wyc

Reputation: 55263

How to modify the following jQuery code so it applies to each li element?

I have the following:

$ul = $('#wpbdp-categories > .wpbdp-categories > li.cat-item > ul');
$('#wpbdp-categories > .wpbdp-categories > li.cat-item > ul').remove();
$('#wpbdp-categories > .wpbdp-categories > li.cat-item').wrapInner('<span>');
$('#wpbdp-categories > .wpbdp-categories > li.cat-item').append($ul);

Which basically turns sometimes like this:

<li>
  <a></a>
  (10)
  <ul></ul>
</li>

into this:

<li>
  <span>
    <a></a>
    (10)
  </span>
  <ul></ul>
</li>

The problem is that the page has many <li></li>.

How to do it so the code is only applied to each li without interfering with the rest?

Upvotes: 1

Views: 75

Answers (2)

Felix Kling
Felix Kling

Reputation: 816312

.each lets you iterate over each of the selected elements and then you can apply the operation to each of them:

$('#wpbdp-categories > .wpbdp-categories > li.cat-item').each(function() {
    $(this).contents().filter(function() {
        return this.nodeName !== 'UL';
    }).wrapAll('<span />');
});

With proper use of jQuery methods, you can also save some explicitly DOM manipulations.

Upvotes: 2

mgibsonbr
mgibsonbr

Reputation: 22007

Iterate over the li elements and perform the individual changes relative to the current element:

$("li").each(function() {
    var content = $(this).clone(true),
    ul = content.children('ul').remove();

    $(this).html($('<span />').append(content.contents()).append(ul));        
});

Update: adapting my answer to the edited code:

$('#wpbdp-categories > .wpbdp-categories > li.cat-item').each(function() {
    var $this = $(this);
    var $ul = $this.children("ul");
    $this.children("ul").remove()
    $this.wrapInner('<span>')
    $this.append(#ul);
});

Upvotes: 2

Related Questions