Search code examples
jquerydomsiblingsclosest

Find closest sibling using jQuery


Given the following DOM

<ul>
     <li data-id="1">
     <li data-id="2">
     <li data-id="3">
     <li data-id="1">
</ul>

We need to find the closest <li>-Element with data-id="1" to the one with data-id="3"

We tried:

$('[data-id=3]').siblings('[data-id=1]').first()

which of course returns the first in DOM and not the closest

We also tried:

$('[data-id=3]').closest('[data-id=1]')

which does not work as it's only returning ancestors.

Thanks for any hints.


Solution

  • Using nextUntil() and prevUntil() you can calculate which direction has the closest sibling and then determine whether to use next() or prev()

    var nextLength = $('[data-id="3"]').nextUntil('[data-id="1"]').length;
    var prevLength = $('[data-id="3"]').prevUntil('[data-id="1"]').length;
    var closestSibling;
    if (nextLength > prevLength) {
      closestSibling = $('[data-id="3"]').prev('[data-id="1"]');
    } else {
      closestSibling = $('[data-id="3"]').next('[data-id="1"]');
    }
    console.log(closestSibling.text());
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <ul>
      <li data-id="1">second closest</li>
      <li data-id="2"></li>
      <li data-id="3"></li>
      <li data-id="1">first closest</li>
    </ul>