apexpals.com
apexpals.com

Reputation: 304

How to get all element siblings in an array in jQuery...?

what i would like to do is get all element siblings in a variable in Jquery to have easy access of all its sibling's properties. As you can see the structure, the siblings don't have ids or classes or even any attributes on them apart from the tag name, but how would i get the element with id=>the_only_id_element to return all its siblings without using $('#the_only_id_element').next().next() .....?

<div id="the_only_id_element"> element one </div>
<div> element two </div>
<div> element three </div>
<div> element four </div>

Upvotes: 0

Views: 1886

Answers (2)

Baumi
Baumi

Reputation: 1767

You should use .siblings():

$('#the_only_id_element').siblings()

Depends on your expectations you can pass as an param the selector.

Demo:

console.log($("#the_only_id_element").siblings());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="the_only_id_element"> element one </div>
<div> element two </div>
<div> element three </div>
<div> element four </div>

Upvotes: 1

Dennisrec
Dennisrec

Reputation: 333

//This one is tested!
var element = $('#the_only_id_element'),
  required_html = $(element).nextUntil(element, 0); //returns array / siblings after each other in array...


//now use array index selector to select any sibling by its position
console.log($(required_html[0]).html())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="the_only_id_element"> element one </div>
<div> element two </div>
<div> element three </div>
<div> element four </div>

Upvotes: 0

Related Questions