Try It Editor
Tip: Press
Ctrl/⌘ + Enter
to Run
▶ Run
Reset
Copy
Download
Code
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>:nth-child() / :nth-of-type()</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <style>.hit{outline:2px solid #2196f3;}</style> </head> <body> <ul id="u"> <li>A</li><li>B</li><li>C</li><li>D</li><li>E</li> </ul> <div> <p>P1</p><span>S1</span><p>P2</p><span>S2</span><p>P3</p> </div> <button id="nth3">li:nth-child(3)</button> <button id="oddli">li:nth-child(odd)</button> <button id="p2type">p:nth-of-type(2)</button> <script> $("#nth3").click(function(){ $("#u li:nth-child(3)").toggleClass("hit"); }); $("#oddli").click(function(){ $("#u li:nth-child(odd)").toggleClass("hit"); }); $("#p2type").click(function(){ $("div p:nth-of-type(2)").toggleClass("hit"); }); </script> </body> </html>
Output