daGrevis
daGrevis

Reputation: 21333

This Keyword + DOM Element in jQuery

I'm creating script that will add , at every unordered list's list element with exception for the last list element - it should end with ;. This should happen for each unordered list!

It's like...

<ul>
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>

<ul>
  <li>d</li>
  <li>e</li>
  <li>f</li>
</ul>

...to:

<ul>
  <li>a,</li>
  <li>b,</li>
  <li>c;</li>
</ul>

<ul>
  <li>d,</li>
  <li>e,</li>
  <li>f;</li>
</ul>

My code looks like this at the moment...

$('ul').each(function(i) {
    var listsLength = $(this + 'li').length;
    $(this + 'li').each(function(j) {
        if (i == (listsLength - 1)) {
            $(this).append(';');
        } else {
            $(this).append(',');
        }
    });
}

I think that problem is this code...

$( this + 'li' )

Any idea how to get the same effect?

Edit:

Fixed it. There was actually syntax error as well and also I used i where j should be placed. Now all works and here's the outcome.

Edit #2:

Just use @lonesomeday code... it's much readable and lightweight!

Upvotes: 3

Views: 219

Answers (4)

Naftali
Naftali

Reputation: 146310

Instead of $( this + 'li' ) do $( 'li', this )

Upvotes: 3

gen_Eric
gen_Eric

Reputation: 227290

this + 'li' will try to convert this to a string, and then concat 'li' to it.

Try this instead:

$('li', this)

Upvotes: 1

Cyril N.
Cyril N.

Reputation: 39889

You could use

$(this).find ('>li').each(...)

instead (if the problem is really here).

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 237975

You can't do this + 'li'. this, in this context, is a DOM element, not a string. To get the effect you want, you'd need $(this).find('li').

Your loop is also unnecessary. You can do something far better with :last-child:

$('ul li:last-child').append(';');
$('ul li:not(:last-child)').append(',');

Those two lines will have the effect you want.

Upvotes: 6

Related Questions