user3758078
user3758078

Reputation:

Find element within HTML string

Is it possible to find an element within a string of HTML rather than from the DOM? Example,

var html = "<div><span class='find-me'></span></div>"

$("html").find(".find-me").remove();

Upvotes: 6

Views: 19398

Answers (4)

jgybrooklyn
jgybrooklyn

Reputation: 1

You could parse the string with DOMParser();

 var html = "<div><span class='find-me'></span></div>"
 dom_doc = new DOMParser().parseFromString(html, "text/xml");
 $(dom_doc).find('#foo').remove();

Upvotes: 0

charlietfl
charlietfl

Reputation: 171698

You are very close, wrap your variable in $()

var $div = $(html);
$div.find(".find-me").remove();

If you want to return to string can do something like:

var htmlString = $('<div>').append($div).html();

Upvotes: 6

danboh
danboh

Reputation: 778

If HTML is a string, you could just use javascript to treat it a string use the replace function, something like:

var html = "<div><span class='find-me'></span></div>"
html = html.replace("find-me", ""); 
alert(html)

In this case, after the replace, html would be:

<div><span class=''></span></div>

Here's the Fiddle

Upvotes: 1

collapsar
collapsar

Reputation: 17288

It is, but it is error-prone and unreliable. Consider <div><span class='find-me'>Devious web designer writes class='find-me' inside a text segment</span></div> - admittedly contrived but imho illustrative.

You are looking for structure information in semi-structured content. Why would you want to make your life harder by searching in _un_structured content ?

Upvotes: 0

Related Questions