views:

114

answers:

3

Hi everyone, can I convert a string to a html object? like:

string s = '<div id="myDiv"></div>';
var htmlObject = s.toHtmlObject;

so that i can later on get it by id and do some changing in its style

var ho = document.getElementById("myDiv").style.marginTop = something;

Thanx a million in advance, Lina

+1  A: 

It will magically become a DOM element when it is written in to the page's HTML.

Coronatus
… which is done how?
David Dorward
A: 

You cannot do it with just method, unless you use some javascript framework like jquery which supports it ..

string s = '<div id="myDiv"></div>'
var htmlObject = $(s); // jquery call

but still, it would not be found by the getElementById because for that to work the element must be in the DOM... just creating in the memory does not insert it in the dom.

You would need to use append or appendTo or after etc.. to put it in the dom first..

Of'course all these can be done through regular javascript but it would take more steps to accomplish the same thing... and the logic is the same in both cases..

Gaby
jQuery is cool but it's only JavaScript
Álvaro G. Vicario
nice approach :)so i can write $(s).css("margin-top") to get the top marginand then modify it and write it to the page...I LOVE this answer :D
Lina
glad you like it Lina :) I think that size/properties would not be getable before inserting it to the DOM.. It makes sense, because an element would be influenced by where in the DOM it gets inserted.. but the reference to the object is still valid, so once you insert it in the DOM you can query its size properties like width/height/margins etc..
Gaby
+2  A: 
var s = '<div id="myDiv"></div>';
var htmlObject = document.createElement('div');
htmlObject.innerHTML = s;
htmlObject.getElementById("myDiv").style.marginTop = something;
pawel
Yep, or just `htmlObject.firstChild` since you know that's where it'll always be.
bobince