Hezron Naresh Hezron Naresh - 3 months ago 20
Javascript Question

Hide and Enable set of Div with same class name in js

I need to hide the all the div with same class name except first div. And then each button click I have to enable other div one by one in js.


<head>
</head>

<body>

<div class ="TextDiv">1</div>
<div class ="TextDiv">2</div>
<div class ="TextDiv">3</div>
<div class ="TextDiv">4</div>
<div class ="TextDiv">5</div>
<input type="submit" value="Show more" onClick>

<script>
function myFunction() {

}
</script>
</body>



Answer

You can filter out the first <div /> in your jQuery selector:

$(".TextDiv:not(:first)")

You are still selecting all the <div /> with the class TextDiv but removing the first one with the :not(:first) part of the selector.

You'll then be able to hide, show or toggle the elements (except the first one).

// Show all except first one
$(".TextDiv:not(:first)").show();

// Hide all except first one
$(".TextDiv:not(:first)").hide();

// Toggle all except first one
$(".TextDiv:not(:first)").toggle();

You can check this JSFiddle for an example. All <div /> except the first one are hidden for example.

Regarding the "Show more" button, you can fetch the last <div /> visible with the TextDiv class, go to the next one and show it:

$("button").on("click", function() {
    $(".TextDiv:visible").last().next().show();
});

You can check this JSFiddle for an example. All <div /> except the first one are hidden, a click on the "Show more" button will show the other <div /> one by one.

If you want to show multiple <div /> at each button press, one approach could be to select all the hidden <div /> with the TextDiv class, select only the first x ones using the slice function and then show them. For example, to show the 5 next hidden ones:

$("button").on("click", function() {
    $(".TextDiv:hidden").slice(0, 5).show();
})

You can check an example on JSFiddle showing the hidden <div /> five-by-five each time you press the "Show more" button.

Comments