user1689591
user1689591

Reputation: 23

Select closest element of certain type - JQuery

I want to select an element with some selector, and the select the closest <p> element to it (note that the p is not nested with the former element). How would I do that? I tried closest(), but that only works if the element is nested.

EDIT: a definition of closest:

<a id="myelement"></a>
<p id="1"></p>
<p id="2"></p>

In this case, p#1 would be selected, assuming #myelement is the element in question.

Upvotes: 0

Views: 7570

Answers (6)

Gui Pinto
Gui Pinto

Reputation: 11

http://jsfiddle.net/gpinto/PTFgG/1/

function findFirstParagraph() {

   var siblings = $('#myElement').siblings();

    siblings.each(function(index) {
        if ( $(this).attr('id') == 1) {
            $(this).css('background-color', 'red');
        }
    });

}​

Upvotes: 1

somdow
somdow

Reputation: 6318

try .find()

there are many functions that do similar things but for me, using something like $(this).find( 'selector here' ) or $(' id or class selector here').find('id/class here') works wonders lol.

Good luck

Upvotes: 0

Teena Thomas
Teena Thomas

Reputation: 5239

try using next() http://api.jquery.com/next/

as per the latest OP edit: jsfiddle.net/KXPwx/9

Upvotes: 0

Chase
Chase

Reputation: 29549

You can use either .siblings() or .next() in your case, but I believe .next would be the better choice if your data is always in the form you posted.

Here's an example:

HTML

<a id="myelement">a</a>
<p id="1">1</p>
<p id="2">2</p>

jQuery

$("#myelement").click(function(){
    console.log($(this).next("p").attr("id"));
    console.log($(this).siblings("p")[0].id);
});​

You'll see that both of the above console logs report and id of 1.

EXAMPLE

Upvotes: 1

Nope
Nope

Reputation: 22339

Given your HTML is:

<a id="myelement"></a>
<p id="1"></p>
<p id="2"></p>

The reason closest() doesn't work is because:

Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

Use next() instead if the 'p' tag will always be the next element:

$('#myelement').next();

However, if you could end up with any additional elements in-between the a and the first p tag than one of the ways to get it is to use nextAll()

$('#myelement').nextAll('p').eq(0);

There is many other ways to get that <p> element for you.

Upvotes: 4

UKWD
UKWD

Reputation: 75

You tried .next() or .prev().. Maybe use .eq(0)??

You can also use .parent() or .parents('.selector')

Upvotes: 0

Related Questions