Select the first <p> element inside the first <div> element:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("div p").first().css("background-color", "yellow"); });/*from w w w .j av a 2 s . c om*/ </script> </head> <body> <h1>Welcome to My Homepage</h1> <div style="border:1px solid black"> <p>This is a paragraph in a div.</p> <p>This is a paragraph in a div.</p> </div><br> <div style="border:1px solid black"> <p>This is a paragraph in another div.</p> <p>This is a paragraph in another div.</p> </div> <p>This is also a paragraph.</p> </body> </html>
The first()
method returns the first element of the selected elements.
$(selector).first()