Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple .find() after selector in jquery chaining?

Basically what the title says - I'm wondering if there's a way to use .find() on the same jQuery selector multiple times. Or maybe using .find() more than once isn't the right way to do this?

Here's what I'm trying to accomplish:

HTML

<div id="foo">
    <h2>A Header</h2>
    <p>Some text</p>
</div>

JS

$("#foo").find("h2").html("New header");
$("#foo").find("p").html("New text");

Webstorm complains about the duplicated jQuery selector. Is there a different/better way to do this?

like image 649
daviddorsey4 Avatar asked Jul 22 '16 15:07

daviddorsey4


3 Answers

You can use next():

$("#foo").find("h2").html("New header")
         .next("p").html("New Text");
like image 116
Sam Coles Avatar answered Nov 09 '22 05:11

Sam Coles


To go back to a previous collection in chaining, we can use end()

$("#foo")
    .find("h2")
        .html("New header")
        .end()
    .find("p")
        .html("New text");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
    <h2>A Header</h2>
    <p>Some text</p>
</div>
like image 23
sabithpocker Avatar answered Nov 09 '22 05:11

sabithpocker


Use .addBack() to back to first selector after using .find() in chaining.

$("#foo").find("h2").html("New header").addBack().find("p").html("New text");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <h2>A Header</h2>
  <p>Some text</p>
</div>
like image 45
Mohammad Avatar answered Nov 09 '22 04:11

Mohammad