将 javascript 字符串转换为 html 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2522422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
converting a javascript string to a html object
提问by bombo
can I convert a string to a html object? like:
我可以将字符串转换为 html 对象吗?喜欢:
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
这样我以后就可以通过 id 获取它并对其样式进行一些更改
var ho = document.getElementById("myDiv").style.marginTop = something;
Thanx a million in advance, Lina
提前一百万,莉娜
采纳答案by Gabriele Petrioli
You cannot do it with just method, unless you use some javascript framework like jquery which supports it ..
你不能只用方法来做到这一点,除非你使用一些像 jquery 这样支持它的 javascript 框架..
string s = '<div id="myDiv"></div>'
var htmlObject = $(s); // jquery call
but still, it would not be found by the getElementByIdbecause for that to work the element must be in the DOM... just creating in the memory does not insert it in the dom.
但是,它仍然不会被 找到,getElementById因为要使其工作,元素必须在 DOM 中……只是在内存中创建不会将它插入到 DOM 中。
You would need to use appendor appendToor afteretc.. to put it in the dom first..
您需要先使用append或appendTo或after等将其放入 dom 中..
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..
当然,所有这些都可以通过常规的 javascript 来完成,但是完成同样的事情需要更多的步骤......并且在这两种情况下逻辑是相同的......
回答by pawel
var s = '<div id="myDiv"></div>';
var htmlObject = document.createElement('div');
htmlObject.innerHTML = s;
htmlObject.getElementById("myDiv").style.marginTop = something;
回答by crownlessking
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;
回答by Ashwin
In addition to Gaby aka's method, we can find elements inside htmlObjectin this way -
除了Gaby aka的方法,我们还可以htmlObject通过这种方式找到里面的元素——
htmlObj.find("#box").html();
Fiddle is available here - http://jsfiddle.net/ashwyn/76gL3/
小提琴在这里可用 - http://jsfiddle.net/ashwyn/76gL3/
回答by Prasad
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
如果您打算使用的浏览器是 Mozilla(插件开发)(不确定 chrome)您可以在 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
希望这可以帮助

