How to remove HTML Element from variable containing HTML? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to remove HTML Element from variable containing HTML? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have got a jQuery var that contains HTML that I’m appending to a page.

I need to remove a HTML element before I append it to the page but I can’t seem to filter it.

for example the variable contains;

<div class="block1"></div>
<div class="block2"></div>

I have tried filtering like this before I append:

var mydata = $(mydata).filter('.block1');

and

var mydata = mydata.filter('.block1');

but none of these work. Any suggestions?

Answer

Filter applied directly to string sometimes give string result, its safe to add element to DOM and then apply filters. Assign html to some temporary element in the DOM, Get the filtered items from this temporary element and assign it to desired element.

$('#TemporaryElemntToAddHtml').html(mydata);

    $('#ElemntToAddHtml .block1').each(function(){
         $('#ElemntToAddHtml').append($(this));
    });

$('#TemporaryElemntToAddHtml').remove();
We are here to answer your question about How to remove HTML Element from variable containing HTML? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji