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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago