1

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');
1
  • Can you please be more specific and put and example of code, that would helps Commented Nov 5, 2015 at 16:08

1 Answer 1

4
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')
Sign up to request clarification or add additional context in comments.

4 Comments

can this be done with angular ? I think it would be much simpler
Alternatively, you could use var div = document.createElement('div'); div.innerHTML = s; var t = div.querySelector('#thing')
@Burawi What's complicated about that? You don't want the nodes on the document, but you want to access them with angular?
@Burawi, Angular connects to your actual document, so the syntax sugar for dom elements only connects to the main document.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.