简体   繁体   中英

How to find the closest li that has the class 'active'

I am trying to generate some jQuery that will find the closest list item that has the class attribute and insert some html directly after it?

I've got the following but this needs work.. its called from an on click event()

$('.controls').on('click.add', function()
{               
       $(this).parent().closest('li.active').insertAfter('<p>HTML</p>');
});

Can anyone assist - in this instance i'd want to select the 3rd li (based upon the class the last 'active' list item) - and insert some simple HTML after it.

<ul class="controls">
  <li class="active"></li>
  <li class="active"></li>
  <li class="active"></li>
  <li class="inactive"></li>
  <li class="inactive"></li>
</ul>
<a href="#" class="add"> Add Prize</a>

"The simplest solution is to use pop, which accesses the last element in the array.

var lastClass = $('div').attr('class').split(' ').pop();

Note that pop also removes the element from the array, but since you aren't doing anything else with it, that's not a problem."

stolen from: jQuery - find last class on the element

Try doing it like this:

$('.add').on('click', function()
{
     $(this).prev().find('li.active:last').after('<p>HTML</p>');

});

Try this:

var $controls = $('.controls');
$('.add').on('click', function() {               
    $controls.find('li.active:last').after('<li>HTML</li>');
});

Also note, that you probably want .after rather than .insertAfter . Plus as pointed in comments you should not insert p as a child of ul , so I changed it to li .

$(".controls li.active").last().after('<p>HTML</p>');

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