I get using ajax from the server a piece of html code. For example, take the following:

<div id='1'>string1</div> <div id='2'>string2</div> <div id='3'>string3</div> 

Then it is inserted into the right place with $('selector').html() but before insertion I need to delete, say a div with id='2' . How to do it exactly before pasting the code into the DOM? I know about regex, but I would like to use jquery and a CSS selector.

  • Make a jQuery object from the response, remove what you need from it, and then paste the rest using append - Grundy
  • @Grundy, how do I convert the response to a jquery object? - koks_rs

1 answer 1

Make a jQuery object from the response, remove what you need from it, and then paste the rest using append

 var html = `<div id='1'>string1</div> <div id='2'>string2</div> <div id='3'>string3</div>` var jQueryObj = $(html); //filter var t = jQueryObj.filter((_,el)=> el.id != 2); $('.selector').append(t); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div class="selector"></div> 

  • but the CSS selector still doesn't apply when using the filter () function? - koks_rs
  • @koks_rs, when the filter is not, but you can wrap it in a container, then the find function will be available in which you can use the selector. - Grundy