1

So, I have a textarea that users are supposed to type codes into.

Ex: <div id="example">blar</div>

How can I evaluate what they enter in the textarea as HTML (as in the DOM) without:

  • jQuery
  • Having to create a new element

For example:

Code: <div id="ex">Blar</div>

My Function:

function parseCode(){
    var code = document.getElementById("code").value;
}

I want to take the value and make it accessible (like code.getElementsByTagName("div")[0].innerHTML);

4
  • 2
    Why the arbitrary-seeming restriction of not creating a new element? Commented May 25, 2012 at 5:30
  • Well, I guess I can create one, kinda with what Chris was saying. Isn't there something like document.evalute? Commented May 25, 2012 at 5:34
  • The innerHTML property is about a good as it gets; you just need a parent element to use. When you set an element's innerHTML property to an HTML string, the string gets parsed and the element gets populated with the result. Commented May 25, 2012 at 5:40
  • @RickyAYoder :you can try the solution I gave. Commented May 25, 2012 at 5:50

1 Answer 1

2
var ele = document.createElement('div');
ele.innerHTML = document.getElementById('code').value;

This does not create a new element on the page itself, only in memory

Sign up to request clarification or add additional context in comments.

3 Comments

And if I assigned it a className/id, I could access it and each of the children as what the user typed as their code, no?
Yes, the html is evaluated when you assign it to the container's innerHTML property. All of the nodes defined in the user submitted HTML become actual child nodes of the newly created div, again, all in memory.
Nice! concise. I didn't think of it :P

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.