bukk530
bukk530

Reputation: 1895

Delete elements in a javascript string

I have a string containing html elements, now I need to select some elements and remove them from the string. In JQuery I tried the following:

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

This is what I expected:

"<ul><li>B</li></ul>"

But I got the same original string. So how can I use CSS selectors to remove html elements from a string?

Upvotes: 0

Views: 106

Answers (1)

jfriend00
jfriend00

Reputation: 707386

You can do it like 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 a couple of issues:

  1. .remove() only operates on the elements in the jQuery object, not on child object so you have to .find() the appropriate child elements before you can remove them.

  2. Since you want the host top level HTML too, you will need the .outerHTML.

  3. You had mistakes in your html_string.

Working jsFiddle: http://jsfiddle.net/jfriend00/x8ra6efz/


You can also save a little jQuery with more chaining like 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/

Upvotes: 4

Related Questions