Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery how to select the first next element(s) that matches a certain selector?

How to select a node after $(this) that matches a certain selector?

eg:

<textarea id="foo"></textarea>
<a href="#">someLink</a>
<a href="#">someOtherLink</a>
<textarea id="bar"></textarea>

With out directly selecting #bar via $("#bar"), how can i select it from within #foo?

like image 984
Babiker Avatar asked Dec 10 '10 06:12

Babiker


People also ask

How do you select the first element with the selector statement?

The :first selector selects the first element. Note: This selector can only select one single element. Use the :first-child selector to select more than one element (one for each parent). This is mostly used together with another selector to select the first element in a group (like in the example above).

Which is the jQuery selector function used for selecting the elements?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

What is slice () method in jQuery?

slice() method constructs a new jQuery object containing a subset of the elements specified by the start and, optionally, end argument. The supplied start index identifies the position of one of the elements in the set; if end is omitted, all elements after this one will be included in the result.

How can I get next sibling in jQuery?

jQuery next() Method The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.


2 Answers

Use the nextAll() method:

$("#foo").nextAll("textarea").first();

Or:

$("#foo").nextAll("textarea:first");

Or even:

$("#foo").nextAll("textarea:eq(0)");
like image 191
Frédéric Hamidi Avatar answered Oct 15 '22 11:10

Frédéric Hamidi


Check out siblings()

$('#foo').siblings('textarea:first').addClass('found');

jsbin demo here

like image 31
jyoseph Avatar answered Oct 15 '22 11:10

jyoseph