[javascript] converting a javascript string to a html object

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

This question is related to javascript html

The answer is


If the browser that you are planning to use is Mozilla (Addon development) (not sure of chrome) you can use the following method in Javascript

function DOM( string )
{
    var {Cc, Ci} = require("chrome");
    var parser = Cc["@mozilla.org/xmlextras/domparser;1"].createInstance(Ci.nsIDOMParser);
    console.log("PARSING OF DOM COMPLETED ...");
    return (parser.parseFromString(string, "text/html"));
};

Hope this helps


In addition to Gaby aka's method, we can find elements inside htmlObject in this way -

htmlObj.find("#box").html();

Fiddle is available here - http://jsfiddle.net/ashwyn/76gL3/


var s = '<div id="myDiv"></div>';
var htmlObject = document.createElement('div');
htmlObject.innerHTML = s;
htmlObject.getElementById("myDiv").style.marginTop = something;

Had the same issue. I used a dirty trick like so:

var s = '<div id="myDiv"></div>';
var temp = document.createElement('div');
temp.innerHTML = s;
var htmlObject = temp.firstChild;

Now, you can add styles the way you like:

htmlObject.style.marginTop = something;