javascriptjqueryjquery-selectorsparagraph

How to select specific paragraph number using JQuery?


I want to select the second paragraph, and can I do that using JQuery but without using an id for the paragraph? Something like accessing a specific node. I tried using $("#p[1]") or $("#p")[1] but it is not correct. I based this logic on the var.childNodes[1]

<div id="info">
    <section>
        <div style="text-align: center">My Biography</div>
        <p>
            My name is JJ.
        </p>
        <p id="one">
            I moved to USA when I was 6 years old.
        </p>
        <button id="show">Show</button>
        <button id="hide">Hide</button>
    </section>
</div>
<script>
 $(document).ready(function () {
        $("#info").ready(change1())
        $("#show").click(function () {
            $("#one").css("visibility", "visible")
        })
        $("#hide").click(function () {
            $("#one").css("visibility", "hidden")
        })
    })

</script>


Solution

  • You can use .eq to get the nth <p> element on the entire page.

    $('p').eq(1) // 2nd paragraph on the page
    

    You can use the regular CSS selector nth-of-type to get paragraph elements that are the nth paragraph to appear in the child list of the parent.

    $('p:nth-of-type(2)') 
    // all paragraph elements that are the second paragraph to appear in their parent