简体   繁体   中英

Remove all label elements from JQuery variable

I use the following:

var transferTemplate = $('#transfersRow').html(); 

in order to store some html code in a variable, which results to:

<div class="form-group row">

     <div class="col-lg-4">
         <label for="inc[1].a">Counterparty</label>
         <input type="text" class="form-control" id="inc[1].a" 
                name="inc[1].a" placeholder="Enter Counterparty">
     </div>

</div>

Now I would like to be able to remove all labels from the html code. I tried:

$(transferTemplate).find(label).remove();

$(transferTemplate).remove('label');

$(transferTemplate).filter('label').remove();

but none works.

First, you need to select the row that you want to remove labels at each row:

Like this:

$(".row").each(function( index ) {
   $(this).find("label").remove(); //find label at each row and remove.
});

I hope that helps.

I think that you are misunderstanding the result of html(). It doesn't return a Jquery DOM object. The result is just a string representation. Just remove the .html() and I'm sure you will be able to call the functions you want.

var transferTemplate = $('#transfersRow');

This returns a string representation of the HTML:

var transferTemplate = $('#transfersRow').html(); 

You could remove the label from this string like this:

$(transferTemplate).find('label').remove();

However, all that does it create a new jQuery object with the HTML minus the label. It won't update the transferTemplate variable.

Instead, you could assign $(transferTemplate) to a new variable.

That would allow you to remove the label and still have access to the updated HTML.

Snippet

 var transferTemplate = $('#transfersRow').html(), template = $(transferTemplate); template.find('label').remove(); $('textarea').val(template.html());
 textarea { width: 100%; height: 10em; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="transfersRow"> <div class="form-group row"> <div class="col-lg-4"> <label for="inc[1].a">Counterparty</label> <input type="text" class="form-control" id="inc[1].a" name="inc[1].a" placeholder="Enter Counterparty"> </div> </div> </div> <hr> <strong>Output</strong> <textarea></textarea>

Well, I guess the correct way is: $(transferTemplate).find('label').remove();

https://api.jquery.com/remove/ Like the penultimate example...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM