简体   繁体   中英

How to select element with specific ID before / after current element using jquery?

I have a website that contains multiple DIVs with the same element that are not organised...

For example:

<div>
   <div id='abc_152142'>
   </div>
   <div id='abc_2353253'>
   </div>
   <div id='abc_3421121'>
   </div>
</div>
<div>
   <div id='abc_44211241'>
   </div>
</div>
<div>
   <div id='abc_541221421'>
   </div>
</div>
<div>
   <div id='abc_654354'> // --> THIS ONE IS SELECTED
   </div>
   <div id='abc_754335'>
   </div>
   <div id='abc_845345'>
   </div>
</div>

So as written in code I am on id 'abc_654354' and want to get to element with the same ID beginning before and after current element.

I have tried:

$(this).prev("div[id^='td_']");
$(this).next("div[id^='td_']");

and that did not get me any results...

IDs are random and the only thing that they have in common is the beginning of ID (in this example i used td_ ).

Thank you for help!

You can simply select the elements based on their indexes in the jQuery collection:

var $e = $('div[id^="td_"]');
var i = $e.index(this);

var $before = $e.eq(i - 1);
var $after = $e.eq(i + 1);

http://jsfiddle.net/QGsza/

If the behavior here for previous:

<div>
   <div id='abc_541221421'>
   </div>
</div>
<div>
   <div id='abc_654354'> // --> THIS ONE IS SELECTED
   </div>
   <div id='abc_754335'>
   </div>
   <div id='abc_845345'>
   </div>
</div>

is that <div id='abc_541221421'> gets returned then:

function getPrevious(){    
    var previous = $(this).prev("div[id^='abc_']");
    if (previous.length > 0)
      return previous;
    return $(this).parent().prev().find("div[id^='abc_']:last")
}

and for next:

function getNext(){    
    var next = $(this).next("div[id^='abc_']");
    if (next.length > 0)
      return next;
    return $(this).parent().next().find("div[id^='abc_']:first")
}

Here's the fiddle.

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