Remove and Add Label using JQuery

Posted on

This is an article focus on the discussion of how to remove and add a label HTML element inside a div HTML element. There is some steps which is needed to be examine carefully when if it is not reviewed correctly, the label HTML element cannot be added to the div HTML element after removing another label HTML element. As an addition, the focus of the article is actually discussing on how to remove and add label using JQuery.

The scenario is displaying a label informing there is no record or data available. The record or data is related to the role of a user. Below is the code taken from the blade view template :

<div class="form-group full-width-chart">
<label class="col-md-2 control-label">Description</label>
<div class="col-md-8">
@if(count($show_user['role']) == 0)
<label class="col-md-4 control-label" id="label-no-role">There is no role</label>

There is a variable which is checked in the above snippet code. That variable is a variable named $show_user which has already defined in the controller and it is passed in a blade view file template named ‘edit.blade.php’. Below is the snippet code which is describing the process mentioned previously :

public function show($id_user) {


$selected_user_role = DB::table('user_role')

$show_user = array("user" => $selected_user, "role" => $selected_user_role);

return view('')->with('show_user' , $show_user);

If there is no role available possessed by the user which the information is being presented then the label containing text of ‘There is no role’ is going to be shown. On the other hand, if there are roles available for that distinct user, the role itself it is going to be printed in an iteration.

Below is the javascript :

<script type="text/javascript">
$("#add_btn_role").click(function () {


$label_role = "<label class=col-md-3 control-label>" + $role_string + "</label>";
$label_server = "<label class=col-md-3 control-label>" + $server_string + "</label>";
$delete = "<input class=col-md-2 type=button value=Delete></input>";

$add_new_record = "<tr><td>" + $role_string + "</td><td>" + $server_string + "</td><td><input type=button value=Delete></input> </tr>";



The line of the snippet code which is quite important to be checked is the following line :


It is assumed that the one which is being removed is the label HTML element which has the id of label-no-role. Instead of only the label, it turns out that the div also seems to be removed. That is why the next process on adding labels failed.

So, in order to remove only the label, just edit the line above as follows :

$("#div-content label").remove();

Since it is the only label available or exist, just add ‘label’ after the div HTML element’s id to specify the label HTML element which is going to be removed.

Leave a Reply