I have HTML in a JavaScript string (containing usual, nested HTML). Using jQuery, can I convert that into a valid HTML element in a single stroke using any of the document.create* functions? My requirement is to use document.getElementById on the created DOM object.
-
HTML should never be in a string in JavaScript.Raynos– Raynos2011-12-25 20:06:05 +00:00Commented Dec 25, 2011 at 20:06
-
3@Raynos: That's not very true. What if you get some pre-rendered HTML from the server?SLaks– SLaks2011-12-25 20:34:13 +00:00Commented Dec 25, 2011 at 20:34
-
1Please edit your question to acknowledge that you are using a convenience library like jQuery. I spent unnecessary time writing native JavaScript code.David Rivers– David Rivers2011-12-25 20:41:14 +00:00Commented Dec 25, 2011 at 20:41
-
@SLaks I agree it's not completely true. What is true however, is HTML should never be in a string in JavaScript application code. It's acceptable as a hidden layer in a library.Raynos– Raynos2011-12-25 21:14:08 +00:00Commented Dec 25, 2011 at 21:14
-
@Raynos: You mean that HTML strings should never explicitly appear in Javascript source code. Yes.SLaks– SLaks2011-12-25 21:25:59 +00:00Commented Dec 25, 2011 at 21:25
|
Show 3 more comments
4 Answers
Take simple nested example.
var dom_string = '<div>xxx<div>yyy</div></div>';
create HTML DOM elements using $() function of jquery and append wherever you want. i have taken 'body' but you can append anywhere.
$(dom_string).appendTo('body');
Alternatively you can implement this with pure javascript:
var dom_target = document.getElementById("target");
dom_target.innerHTML = dom_string;
2 Comments
Raynos
Try to avoid using jQuery when it's not asked for, it's just confusing.
James Poulose
The Jquery & vanilla versions do not seem to be the same. JQ version just appends to the target (as the api name implies, but the vanilla version just replaces the entire
innerHTML.Create a dummy element and set its innerHTML to your HTML string.
2 Comments
Vineel Kumar Reddy
Thanks. May I know on what elements can I invoke getElementById apart from on document object.
P K
after setting innerHTML, your DOM part of string behave as real DOM elements so you can apply getElementById on every nested tag of string,
// Construct a container as a placeholder for your content
var container = document.createElement('div');
container.id = 'container';
// Inject the container into the DOM
document.body.appendChild(container);
// Populate the injected container with your content
container.innerHtml = '<p id="pTag">I am a <em>P</em> tag with some <strong>nested markup</strong>.</p>';
Comments
To convert Html text into a Jquery-Object use the $() function:
div = '<div>hello world</div>';
$div = $(div);
But as others have noted in most cases you don't need that because DOM manipulation functions like append() and prepend() will accept plain text, so
$('body').append('<div>hello world</div>');
is absolutely fine.