問題描述
我正在運行 GM_xmlhttpRequest
(在 Greasemonkey 腳本中)并將 responseText
存儲到新創建的 HTML 元素中:
I'm running GM_xmlhttpRequest
(in a Greasemonkey script) and storing the responseText
into a newly created HTML element:
var responseHTML = document.createElement('HTML');
...
onload: function() { responseHTML.innerHTML = response.responseText; }
然后我試圖在 responseHTML
:
console.log(responseHTML.getElementsByTagName('div'));
console.log(responseHTML.getElementById('result_0'));
第一個工作正常,但不是第二個.有什么想法嗎?
The first works fine, but not the second. Any ideas?
推薦答案
getElementById
不是 HTML 元素的方法.它是文檔節點的一個方法.因此你不能這樣做:
getElementById
is not a method of HTML elements. It is a method of the document node. As such you can't do:
div.getElementById('foo'); // invalid code
您可以通過遞歸遍歷 children
來實現自己的函數來搜索 DOM.在較新的瀏覽器上,您甚至可以使用 querySelector
方法.對于最小的開發,您可以使用 jQuery 或 sizzle.js(jQuery 背后的查詢引擎)等庫.
You can implement your own function to search the DOM by recursively going through children
. On newer browsers you can even use the querySelector
method. For minimal development you can use libraries like jQuery or sizzle.js (the query engine behind jQuery).
這篇關于“getElementById 不是函數"嘗試解析 AJAX 響應時?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!