Reputation: 23
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
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
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
Reputation: 5239
try using next()
http://api.jquery.com/next/
as per the latest OP edit: jsfiddle.net/KXPwx/9
Upvotes: 0
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
.
Upvotes: 1
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
Reputation: 75
You tried .next() or .prev().. Maybe use .eq(0)??
You can also use .parent() or .parents('.selector')
Upvotes: 0