3

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?

2
  • mydata is already set somewhere? Have you tried $("div").filter('.block1').remove(); or perhaps $("div").filter(return $(this).hasClass(".block1")).remove();? Commented Oct 11, 2012 at 16:03
  • Works well. jsfiddle.net/rns4h Commented Oct 11, 2012 at 16:04

5 Answers 5

2

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();
Sign up to request clarification or add additional context in comments.

Comments

1

Try .remove()

$('.block1').remove();

OR

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

1 Comment

This just returns mydata as null?
0

$.filter doesn't do what you think it does.

http://api.jquery.com/filter/

I would try $(mydata).remove('.block1');

Comments

0

Did you try the .remove function?

  var mydata = $('<div class="block1"></div>
                 <div class="block2"></div>');
  mydata.remove('.block1');

4 Comments

I think you confused selector with function... Just to be correct.
@Mario De Schaepmeester, yes fixed
This doesn't seem to work. I wonder if it's got anything to do with the variable being passed back from an ajax request, but I can't see how this variable would be any different.
are you converting the ajax result to jquery element? ex: $(myresult)
0

Use the splice native method to remove at the element index, and remove 1 item.

mydata.splice( mydata.filter('.block1').index(), 1 );

Note with that splice do not add mydata = mydata.splice(..) as that will return the removed element.

Otherwise use jQuery's remove method as some people already said.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.