Spilarix
Spilarix

Reputation: 1468

How to simplify this jquery tree traversal?

HTML

...
<a id="delete1" href="http://www.example.com">TEST</a>
<p>First</p>
<p>Second</p>
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>
<div id="hidden-qsd">123</div>
...

JS

var id = $('#delete1').nextUntil("div[id^='hidden']").next().last().attr('id');

I'd like to get the id of the closest "div" starting with "hidden" located after the link "#delete1".
This previous code is working but I think there is a simpler way to do it.

Upvotes: 1

Views: 99

Answers (2)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

$('#delete1').nextAll('[id^="hidden"]').attr('id')

nextAll() is enough

example jsbin: http://jsbin.com/usowej/3/edit

Note: if you have more than one element whose id is starting with hidden just use

$('#delete1').nextAll('[id^="hidden"]:first').attr('id')

to retrieve just the first occurence, see http://jsbin.com/usowej/4/edit

Upvotes: 2

Bogdan
Bogdan

Reputation: 44526

You can use nextAll(selector) to get the next siblings after the element:

var id = $('#delete1').nextAll("div[id^='hidden']").prop('id');

http://api.jquery.com/nextAll/

Upvotes: 1

Related Questions