Conceal or Erase
When dealing with changing DOM elements, is it better to hide them or delete them? Consider that the environment may change frequently and that elements can have various event callbacks.
Hide:
What is the best approach when hiding elements? If clicking a button should hide multiple items, you can choose to hide them individually or utilize CSS rules for this purpose.
Option 1:
<style>
.superContent{/*...*/}
.superContent.noEdit .occultable{
display:none;
}
</style>
<form class=”superContent” action=”...”>
<label>Name</label>
<input type=”text” />
<input type=”submit” class=”occultable” value=”send”/>
</form>
<button id=”hideAll”>Edit</button>
<script type=”text/javascript”>
$(“#hideAll”).click(function(){
$(“.superContent”).toggleClass(“noEdit”);
});
</script>
Alternatively, you could simply hide the desired items (which may be a few or many):
Option 2:
<script type=”text/javascript”>
$(“#hideAll”).click(function(){
$(“.occultable”).toggle();
});
</script>
Remove:
To modify the DOM, you also have the option of deleting unwanted items and re-inserting them later.
Option 3:
<form class="superContent">
<label>Name</label>
<input type="text" />
<input id="sendbutton" type="submit" class="occultable" value="send"/>
</form>
<button id="hideAll">Edit</button>
<script type=”text/javascript”>
$("#hideAll").click(function(){
if( $(".superContent").find("#sendbutton").length>0 ){
$(".superContent").find("#sendbutton").remove();
}
else{
$(".superContent").append('<input id="sendbutton" type="submit" class="occultable" value="send"/>');
}
});
</script>
These are just samples. In a UI with numerous elements, which approach do you consider the most optimal? Which one minimizes memory leaks and maximizes performance?
Some JavaScript frameworks like kendo-ui favor removing elements, while jQueryUI tends to hide them. However, in scenarios like the Tab sortable widget, jQuery temporarily hides tabs as the user drags them.