简体   繁体   中英

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.

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.

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

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');
        }
    });

}​

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM