String to jQuery object, how to remove elements

I am trying to manipulate some html that is in a text box (and not part of the page), but I want to be able to execute jQuery functions on it.

Here I am trying to remove a div with attr 'my_id' from 1234, but the resulting data remains the same?

var data = "<div>something<div my_id='1224'>blah</div><div my_id='1234'>xx123</div></div>"; var id = '1234'; $(data).remove('[my_id="'+id+'"]'); alert($(data).html()); 

Obviously, a warning is just used for debugging.

+4
source share
2 answers
 var data = "<div>something<div my_id='1224'>blah</div><div my_id='1234'>xx123</div></div>"; var id = '1234'; var $data = $(data); // create elements from the string, and cache them $data.find('[my_id="'+id+'"]').remove(); // find and remove the nested element alert($data.html()); // alert the resulting HTML 
  • You provided a .remove() selector that only works on top level elements. The target item is nested.

  • When you did alert($(data).html()); , you used the original string that was not changed. You need to create elements, reference the jQuery object, do your manipulation, and then use the same jQuery object to see the result.

+2
source

EDIT

Deleting a workaround for non-proprietary elements

Use the data prefix to place custom attributes on elements:

 <div data-my_id='1224' 

And then:

 $(data).find('div[data-my_id="' + id + '"').remove(); 

Or just just use the regular id on the targeting div:

  <div id='1224' 

Then you can delete:

 $(data).find('#' + id).remove(); 
+1
source

Source: https://habr.com/ru/post/1384239/


All Articles