Disable contents of a div with JavaScript/jQuery
This post will discuss how to disable the contents of a div in JavaScript and jQuery.
1. Using jQuery
The idea is to disable click events inside div with jQuery and CSS. This can be done by setting pointer-events CSS property with the help of jQuery’s .addClass() function.
JS
|
1 2 3 |
$(document).ready(function() { $("#container").addClass("disable-div"); }); |
CSS
|
1 2 3 |
.disable-div { pointer-events: none; } |
HTML
|
1 2 3 4 |
<div id="container"> <label>Enter your name: <input type="text"></label> <button id="submit">Submit</button> </div> |
Alternatively, you can use the .children() method to get all the children of the div element in the DOM tree and set the HTML boolean disabled attribute to true with the .prop() method.
JS
|
1 2 3 |
$(document).ready(function() { $("#container").children().prop('disabled', true); }); |
HTML
|
1 2 3 4 5 |
<div id="container"> <label>Enter your name:</label> <input type="text"> <button id="submit">Submit</button> </div> |
You can also use the :input selector with a parent selector, which selects all form controls like input, textarea, select, and button elements.
JS
|
1 2 3 |
$(document).ready(function() { $("#container :input").prop('disabled', true); }); |
HTML
|
1 2 3 4 |
<div id="container"> <label>Enter your name: <input type="text"></label> <button id="submit">Submit</button> </div> |
To select all elements, use the special string *.
JS
|
1 2 3 |
$(document).ready(function() { $('#container *').prop('disabled', true); }); |
HTML
|
1 2 3 4 5 |
<div id="container"> <label>Enter your name:</label> <input type="text"> <button id="submit">Submit</button> </div> |
2. Using JavaScript
In plain JavaScript, you can get all the children of the div and disable them within a loop. The idea is to use the getElementsByTagName() method, which returns a collection of elements with the given tag name. To get all elements, use the * string.
JS
|
1 2 3 4 |
var childNodes = document.getElementById("container").getElementsByTagName('*'); for (var node of childNodes) { node.disabled = true; } |
HTML
|
1 2 3 4 |
<div id="container"> <label>Enter your name: <input type="text"></label> <button id="submit">Submit</button> </div> |
That’s all about disabling the contents of a div in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)