Burawi
Burawi

Reputation: 471

AngularJS get dom element from string

I have a string containing html code, I want to get from it elements by css selectors like I do with angular.element without displaying it on the page.

How can I do that ?

EDIT

for instance, I have this variable:

var s = '<div id="hello">Hello</div><div id="world">World</div>';

Is there any way to get the div wih id='world' ? like:

s.function('#world');

Upvotes: 1

Views: 2608

Answers (1)

Aaron Gates
Aaron Gates

Reputation: 469

var s = "<div id=\"thing\">Hello</div>";
var d = new DOMParser();
var p = d.parseFromString(s, "text/html");
var t = p.getElementById('thing');

Alternatively, you could use:

var div = document.createElement('div');
div.innerHTML = s;
var t = div.querySelector('#thing')

Upvotes: 4

Related Questions