Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide the 3rd paragraph out of 5 paragraphs on a click of a button, with out assigning any class or id to the paragraphs

I have five paragraphs on my front end as below:

<form id="form1" runat="server">
    <div id="div">
        <p>para1</p>
        <p>para2</p>
        <p>para3</p>
        <p>para4</p>
        <p>para5</p>
        <asp:Button id="button" runat="server" Text="Click to hide para3!" />     
    </div>
</form>

In JS I wrote the following:

 $("#button").click(function () {
    $('#div').find('p').hide();
    return false;
});

I know when I click on the button it hides all the p tags, so it would be great if any one can tell me how I would be able to hide the third paragraph only.

like image 843
Mohammed Abrar Ahmed Avatar asked Jun 06 '16 07:06

Mohammed Abrar Ahmed


3 Answers

You can achieve this by using the eq() method to specify which element in a matched set you want to retrieve by its index. As the index is zero-based, to get the third element would be eq(2).

Also note that you should hook to the submit event of the form element, not the click event of the button. Firstly because it's much better practice and secondly because you're using ASP.Net web forms which means that the id attributes will be over-written on any runat="server" elements when the HTML is generated by the server (unless you specify a setting but that's not specifically relevant here).

Try this:

<form id="form1" runat="server">
    <div id="div">
        <p>para1</p>
        <p>para2</p>
        <p>para3</p>
        <p>para4</p>
        <p>para5</p>
        <asp:Button id="button" runat="server" Text="Click to hide para3!" />     
    </div>
</form>
$("form").submit(function(e) {
    e.preventDefault();
    $('#div').find('p:eq(2)').hide();
});

Working example

like image 100
Rory McCrossan Avatar answered Nov 12 '22 10:11

Rory McCrossan


jQuery's nth-child(n) selector selects all elements that are the nth child, regardless of type, of their parent. So you can do it with this way:

$("#button").click(function () {
    $('#div p:nth-child(3)').hide();
    return false;
});

like image 38
kkakkurt Avatar answered Nov 12 '22 09:11

kkakkurt


You can simply use jquery's .eq(). this method reduce the set of matched elements to the one at the specified index.

For more Jquery's.eq()

$("form").submit(function(e) {
    e.preventDefault();
    $('#div p').eq(2).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form id="form1">
    <div id="div">
        <p>para1</p>
        <p>para2</p>
        <p>para3</p>
        <p>para4</p>
        <p>para5</p>
        <button id="button">Click to hide para3</button>
    </div>
</form>
like image 3
pradeep1991singh Avatar answered Nov 12 '22 10:11

pradeep1991singh