Laravel Laravel - 3 years ago 281
CSS Question

jQuery insert after li element with attribute

I have list:

<ul class="customList">
<li data-featured="1">First item</li>
<li data-featured="0">Another item</li>
<li data-featured="0">Last item..</li>

How can I insert my custom
? If all featured 0, then insert as first
.. Thanks in advance.

var self = this;
self.scope.find('.customList').prepend(myCustomItem); //this code inserts in begin, not after featured items..
$(myCustomItem).insertAfter('[data-featured="1"]'); //I've tried to build something.. but this fails

Sorry for my bad English


looks like is working, but when there is any data-featured=1, then nothing happens. Any suggestions?

Answer Source

You can first use the jQuery attribute selector [attribute=value]: to check if li with data-featured="1" is exist or not. If exist then use the jQuery method .insertAfter() to insert the new li after it and if not then insert new li at the first position using .insertBefore().

if($('.customList li[data-featured="1"]').length>0)
      $("<li data-featured='99'>NEW ITEM</li>").insertAfter('.customList li[data-featured="1"]');
      $("<li data-featured='99'>NEW ITEM</li>").insertBefore('.customList li:first');
<script src=""></script>
<ul class="customList">
    <li data-featured="0">First item</li>
    <li data-featured="0">Another item</li>
    <li data-featured="0">Last item..</li>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download