Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select the first sibling of a certain element type with jQuery?

Tags:

jquery

The HTML is structured like this:

<div id="myDiv"></div>
<img src="" />
<p></p> // I want to select this element 
<h1></h1>
<p></p>
<h2></h2>

Based on my start element <div id="myDiv"> There are several more <p> siblings but I only want the first one, as seen in the code.

How can I achieve this?

like image 524
Weblurk Avatar asked Nov 13 '13 08:11

Weblurk


People also ask

Which selector select the first element of the tag in jQuery?

The :first selector selects the first element.

How can I find siblings in jQuery?

jQuery siblings() MethodThe siblings() method returns all sibling elements of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward and backwards along siblings of DOM elements.

How do I target a specific element in jQuery?

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.

Which function in jQuery is used to grab a previous sibling element?

The prev() method returns the previous sibling element of the selected element. Sibling elements are elements that share the same parent.


1 Answers

jQuery('#myDiv').siblings('p:first')

or

jQuery('#myDiv').siblings('p').first()

would do the trick

like image 108
OlivierH Avatar answered Oct 03 '22 13:10

OlivierH