Categories: Development

jQuery show, hide, remove and create element example

Using jQuery to show, hide and remove HTML content as well as the differences between using hide and remove.

Hide

In jQuery hide() sets the element to display: none; meaning the user can no longer see it and its former place on the screen will be filled.

$("#elementId").hide();

Show

show() will undo this (with display: block;) and make the targeted element re-appear.

$("#elementId").show();

Remove

remove() as per its name will remove (delete) the element and everything inside it. You cannot use show() after using a remove().

$("#elementId").remove();

When using hide() the content is still in the source code, even though the user/viewer cannot see it. With remove() the element will not be found in the source code of the current pages state.

Create (append)

Creating HTML elements with jQuery can be best done with append(). Which will insert content at the end of the targeted element, but still inside it.

$("#targetId").append(`<div class="card-class"><p>The card body text</p></div>`);

This would work as

<div id="targetId">
<h1>Target Id text</h1>
<div class="card-class"><p>The card body text</p></div>
</div>

As you see it went inside the element.

Working example

A working example with alerts for various states can be found here at CodePen.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago