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.