开发者

converting a javascript string to a html object [duplicate]

This question already has answers here: Creating a new DOM element from an HTML string using built-in DOM methods or Prototype (29 answers) Closed 8 years ago.

can I convert a string to a html object? like:

str开发者_JAVA百科ing 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


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


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..


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;


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/


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜