ArticleZip > What Is The Javascript Equivalent Of Jquerys Hide And Show Duplicate

What Is The Javascript Equivalent Of Jquerys Hide And Show Duplicate

Have you ever been coding away in JavaScript and wished there was a simple way to hide and show elements just like you can do with jQuery? Well, you're in luck! In JavaScript, the equivalent of jQuery's hide() and show() functions can be achieved using plain JavaScript.

To hide an element in JavaScript, you can set its style.display property to 'none'. This will effectively hide the element from view on the webpage. To show the element again, you can set its style.display property back to an empty string, which will make the element visible once more.

For example, let's say you have an element with the id 'myElement' that you want to hide:

Html

<div id="myElement">
    This is the element you want to hide.
</div>

You can hide this element using JavaScript like this:

Javascript

document.getElementById('myElement').style.display = 'none';

And to show it again, you can use the following code:

Javascript

document.getElementById('myElement').style.display = '';

This is the basic equivalent of jQuery's hide() and show() functions in JavaScript. By manipulating the style.display property of an element, you can easily hide and show elements on your webpage without the need for jQuery.

Additionally, you can take this a step further by creating functions in JavaScript that encapsulate this behavior. For example, you could define a hideElement() function like this:

Javascript

function hideElement(elementId) {
    document.getElementById(elementId).style.display = 'none';
}

function showElement(elementId) {
    document.getElementById(elementId).style.display = '';
}

With these functions in place, you can now hide and show elements by simply calling these functions with the id of the element you want to manipulate. This can help make your code cleaner and more modular, allowing for easier maintenance and reuse.

So, the next time you find yourself needing to hide or show elements in JavaScript just like you would in jQuery, remember that you can achieve the same functionality using plain JavaScript with a few simple lines of code. Happy coding!

×