JavaScript getElementsById 从变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27223478/
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
JavaScript getElementsById from variable
提问by tomsk
i would like to ask you how can i get elements by id from variable in JavaScript. For example i have in JavaScript variable which contains html source code and i would like to get elements from this variable.
我想问你如何通过 id 从 JavaScript 中的变量获取元素。例如,我有一个包含 html 源代码的 JavaScript 变量,我想从这个变量中获取元素。
For example:
例如:
var html = "<html><body><div id='test'>Hi</div> ... lot of code ... <div id='test'>Hi</div><div id='test'>Hi</div> ... lot of code ... </body></html>";
var get = html.getElementsById("test");
But it's not working
但它不起作用
Thank you so much for any help
非常感谢您的帮助
回答by deitch
You cannot do what you are doing. You have a few problems.
你不能做你正在做的事情。你有几个问题。
getElementById
is singular, not plural (getElementsById
). This is because in properly formatted html, every id must be unique. Browsers allow it to slip by, but it is one element onlygetElementById()
is a method on the DOMnot on a stringas you are doing above.
getElementById
是单数,不是复数(getElementsById
)。这是因为在格式正确的 html 中,每个 id 必须是唯一的。浏览器允许它溜走,但它只是一个元素getElementById()
是DOM上的一个方法,而不是像上面所做的那样在字符串上。
There are three ways that I can think of to do this:
我可以想到三种方法来做到这一点:
You could try creating a regex to do it, but it would be messy. You would need to find every occurrence of `id\s+=\"'+myVar+\"' and then find the element surrounding it. Very messy, but doable.
您可以尝试创建一个正则表达式来执行此操作,但这会很麻烦。您需要找到每个出现的 `id\s+=\"'+myVar+\"' 然后找到它周围的元素。非常凌乱,但可行。
Better is to load it into a browser and then do document.getElementById()
更好的是将其加载到浏览器中然后执行 document.getElementById()
Even simpler is to use jquery
更简单的是使用jquery
$(html).find('#test');
回答by user3728205
You could try DOMParser
你可以试试DOMParser
var html = "<html><body><div id='test'>Hi</div> ... lot of code ... <div id='test'>Hi</div><div id='test'>Hi</div> ... lot of code ... </body></html>";
var parser = new DOMParser();
var doc = parser.parseFromString(html, 'text/html');
var get = doc.getElementsById("test");