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.
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
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;
});
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>
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