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?
You can use next():
$("#foo").find("h2").html("New header")
.next("p").html("New Text");
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With