Javascript javascript从div中获取html或文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4357145/
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 get html or text from div
提问by Cyber Junkie
This is easy in jquery but how about plain javascript?
这在 jquery 中很容易,但是普通的 javascript 怎么样?
The code is for the Google image search API. I want to search images that match the html or preferably text inside a div.
该代码用于 Google 图片搜索 API。我想搜索与 html 匹配的图像,或者最好是 div 中的文本。
var searchThis = document.getElementById('imgToFind'); //get HTML, or text from div
// Find images
imageSearch.execute(searchThis); //search image
The HTML
HTML
<div id="imgToFind">PlayStation</div>
The result should be images of playstation. Instead I get these
结果应该是游戏机的图像。相反,我得到了这些
dosic ois - 123
剂量 ois - 123
IE8 javascript returns [object HTMLDivElement] instead [
IE8 javascript 返回 [object HTMLDivElement] 而不是 [
Loving Hand
爱心之手
And other irrelevant images. I wonder what Google searches for.. think the second one is giving me a hint.
以及其他不相关的图像。我想知道谷歌搜索什么......认为第二个给了我一个提示。
回答by Shiv Deepak
its var searchThis = document.getElementById('imgToFind').innerHTML;
它的 var searchThis = document.getElementById('imgToFind').innerHTML;
to extract only text you can do:
只提取文本你可以这样做:
element = document.getElementById('imgToFind');
var searchThis = element.textContent || element.innerText;
回答by Damien-Wright
var searchThis = document.getElementById('imgToFind').innerHTML;
var searchThis = document.getElementById('imgToFind').innerHTML;
will grab the contents of the element :)
将获取元素的内容:)
回答by Tim Down
If you want just the text within an element, you can use textContent
in the more standards compliant browsers (i.e. not IE) and innerText
in IE. They're not identical in all casesbut for your purposes they may well be.
如果您只想要元素中的文本,您可以textContent
在更符合标准的浏览器(即非 IE)和innerText
IE 中使用。它们并非在所有情况下都相同,但就您的目的而言,它们很可能是相同的。
var el = document.getElementById("foo");
var text = el.textContent || el.innerText;