onclick show 10 elements

How to Show 10 Elements on Click in HTML

If you want to show 10 elements on click, you can use the onclick event handler in HTML. This event handler is used to trigger a function when an element is clicked. Here is an example of how you can show 10 elements on click:


<!DOCTYPE html>
<html>
<head>
<title>Show 10 Elements on Click</title>
</head>
<body>

<button onclick="showTenElements()">Show 10 Elements</button>

<div id="container">
<ul id="elements">
<li>Element 1</li>
<li>Element 2</li>
<li>Element 3</li>
<li>Element 4</li>
<li>Element 5</li>
<li>Element 6</li>
<li>Element 7</li>
<li>Element 8</li>
<li>Element 9</li>
<li>Element 10</li>
</ul>
</div>

<script type="text/javascript">
function showTenElements() {
var elements = document.getElementById("elements").getElementsByTagName("li");

for (var i = 0; i < elements.length; i++) {
if (i < 10) {
elements[i].style.display = "block";
}
else {
elements[i].style.display = "none";
}
}
}
</script>

</body>
</html>

Explanation

In the above code, we have a button with an onclick event handler that calls the showTenElements function. The function gets all the li elements inside the ul with the id "elements" using the getElementsByTagName method. It then loops through each element and checks if its index is less than 10. If it is, it sets the display property of the element to "block" to show it. If it is not, it sets the display property to "none" to hide it.

The CSS property "display" controls how an element is displayed on a web page. The value "block" makes an element take up the full width available and starts on a new line. The value "none" hides an element and removes it from the flow of the page.

This is just one way of showing 10 elements on click. You can use different HTML elements, CSS properties and JavaScript methods to achieve the same result. For example, you can use the jQuery library to simplify the code:


$(document).ready(function() {
    $("#show-elements").click(function() {
        $("li:lt(10)").toggle();
    });
});

This code uses the jQuery library to select and toggle the display of the first 10 li elements when a button with the id "show-elements" is clicked.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe