jquery - Delete elements in a javascript string -


i have string containing html elements, need select elements , remove them string. in jquery tried following:

html_string = "<ul><li data-delete>a<li><li>b</li></ul>"; html_clean_string = $(html_string).remove('[data-delete]').html(); 

this expected:

"<ul><li>b</li></ul>" 

but got same original string. how can use css selectors remove html elements string?

you can this:

var html_string = "<ul><li data-delete>a</li><li>b</li></ul>"; var elems = $(html_string); elems.find('[data-delete]').remove(); var html_clean_string = elems[0].outerhtml; 

you had couple of issues:

  1. .remove() operates on elements in jquery object, not on child object have .find() appropriate child elements before can remove them.

  2. since want host top level html too, need .outerhtml.

  3. you had mistakes in html_string.

working jsfiddle: http://jsfiddle.net/jfriend00/x8ra6efz/


you can save little jquery more chaining this:

var html_string = "<ul><li data-delete>a</li><li>b</li></ul>"; var html_clean_string = $(html_string).find('[data-delete]').remove().end()[0].outerhtml; 

working jsfiddle:http://jsfiddle.net/jfriend00/wmtascxf/


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -