This is the keyword + DOM element in jQuery

I am creating a script that will add in each unordered element of the list, with an exception for the last element of the list - it should end in :. This should happen for every unordered list!

I like...

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

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

... at:

<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 the problem is in this code ...

$( this + 'li' )

Any idea how to get the same effect?

Edit:

Fixed. There was also a syntax error, and also I used i where j should be placed. Now everything works and here is the result .

Edit # 2:

Just use the @lonesomeday code ... it's very readable and easy!

+3
source share
4 answers

this + 'li'. this, , DOM, . , $(this).find('li').

. - :last-child:

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

.

+6

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

+3

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

Try this instead:

$('li', this)
+1
source

you can use

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

instead (if the problem is really here).

0
source

All Articles