Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to close list items with JavaScript?
To close list items with JavaScript, the code is as follows −
Example
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
* {
box-sizing: border-box;
}
ul {
list-style-type: none;
padding: 0;
margin: 0;
}
ul li {
border: 1px solid rgb(221, 221, 221);
background-color: #5a5cec;
color: white;
padding: 12px;
text-decoration: none;
font-size: 18px;
display: block;
position: relative;
font-weight: 500;
}
ul li:hover {
background-color: rgb(43, 0, 145);
}
.close {
cursor: pointer;
position: absolute;
top: 50%;
right: 0%;
padding: 12px 16px;
transform: translate(0%, -50%);
}
.close:hover {
background: red;
}
</style>
</head>
<body>
<h1>Closable List Items Example</h1>
<h2>Click 'x' on the list items to close them</h2>
<ul>
<li>Cat<span class="close">×</span></li>
<li>Lion<span class="close">×</span></li>
<li>Tiger<span class="close">×</span></li>
<li>Leopard<span class="close">×</span></li>
<li>Cheetah<span class="close">×</span></li>
</ul>
<script>
var closebtns = document.querySelectorAll(".close");
Array.from(closebtns).forEach(item => {
item.addEventListener("click", () => {
item.parentElement.style.display = "none";
});
});
</script>
</body>
</html>
Output
The above code will produce the following output −

On clicking the ‘x’ on some items −

Advertisements