简体   繁体   中英

How to insert after a specific element but before another element

Explaining by example:

<li data-owner="1"></li>
<li data-id="1"></li>
<li data-id="2"></li>
(insert here)
<li data-owner="2"></li>

I want to insert between data-owner="1" and data-owner="2" , and insert last - just above data-owner="2" .

This do my first requirement:

$('li[data-owner="1"]').after('<li data-id="3"></li>');

But this will insert here:

<li data-owner="1"></li>
(insert here)
<li data-id="1"></li>
<li data-id="2"></li>
<li data-owner="2"></li>

Is there a way to make it insert after one element, and then move down until it finds another element and insert before that? Or find the next element li[data-owner] after a specific element li[data-owner="2"] and insert before that?

I cannot use $('li[data-owner="2"]').before('<li data-id="3"></li>'); because I do not know the specific value of data-owner of the element I want to insert before.

You are going to want to find the next list element with a data id, and then place your insertion before that element. This can be done using nextAll . The example is broken out to show the steps clearer as opposed to being simply chained.

 var owner = 1; var currentOwner = $('li[data-owner='+owner+']'); var nextOwner = currentOwner.nextAll('li[data-owner]:first'); nextOwner.before('<li data-id="3">(insert: li data-id="3")</li>'); //1-liner: $('li[data-owner=1']').nextAll('li[data-owner]:first').before('<li data-id="3">(insert)</li>') 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <li data-owner="1">data-owner="1"</li> <li data-id="1">data-id="1"</li> <li data-id="2">data-id="2"</li> <li data-owner="2">data-owner="2"</li> 

Something along these lines?

<ul>
<li data-owner="1">a</li>
<li data-id="1">b</li>
<li data-id="2">c</li>
<li data-owner="2">d</li>
</ul>

javascript:

var owner_flag = 0;
jQuery("li[data-owner]").each(function(){
    if(owner_flag == 1)
    {
        owner_flag == 0;
        jQuery(this).before('<li data-id="3">next</li>');
    }
    if(jQuery(this).attr("data-owner") == "1")
    {
        owner_flag = 1;
    }
});

https://jsfiddle.net/u7m5mkL6/

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