开发者

jQuery: Select a <p> tag within a <li>

I'm trying to use jquery to fade out a <p> tag within a <li> when a delete button is selected.

<ul>
    <li>
        <p>Here is some text!</p>
        <span class="delete">Delete</span>
    <li>
<ul>

Here is my jQuery so far:

$(".delete").click(func开发者_开发百科tion(){
    //Needs to select the <p> tag within the same <li> 
    $("p").fadeOut(); 
});


With your structure as quoted, simply:

$(".delete").click(function(){
    //Needs to select the <p> tag within the same <li> 
    $(this).prev("p").fadeOut(); 
});

If it's possible the p won't be the immediate predecessor to the delete link, then you can do this:

$(".delete").click(function(){
    //Needs to select the <p> tag within the same <li> 
    $(this).closest("li").find("p").fadeOut(); 
});

...which will fade out all p elements it finds in the li, or this:

$(".delete").click(function(){
    //Needs to select the <p> tag within the same <li> 
    $(this).closest("li").find("p").first().fadeOut(); 
});

...which will fade out the first p element it finds in the li, or this:

$(".delete").click(function(){
    //Needs to select the <p> tag within the same <li> 
    $(this).prevAll("p").first().fadeOut(); 
});

...which will fade out the first sibling it finds working backward from the delete link.

References:

  • prev - find the immediate previous sibling, or nothing if it doesn't match the selector
  • closest - find the nearest ancestor matching a selector
  • find - find all descendants matching a selector
  • prevAll - find all previous siblings matching a selector, in reverse document order (e.g., working backward from the current element)
  • first - only grab the first element in the current set


$(".delete").click(function () {
    //Needs to select the <p> tag within the same <li> 
    $(this).closest("li").find("p").fadeOut(); 
});

…or you use parent() instead of closest().

If the <p> always precedes the <span>, you can also do:

$(".delete").click(function () {
    //Needs to select the <p> tag within the same <li> 
    $(this).prev("p").fadeOut(); 
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜