13

This is easy in jquery but how about plain 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.

var searchThis = document.getElementById('imgToFind'); //get HTML, or text from div

// Find images
imageSearch.execute(searchThis); //search image

The HTML

<div id="imgToFind">PlayStation</div>

The result should be images of playstation. Instead I get these

1 dosic ois - 123

alt text IE8 javascript returns [object HTMLDivElement] instead [

alt text Loving Hand

And other irrelevant images. I wonder what Google searches for.. think the second one is giving me a hint.

Cyber Junkie
  • 784
  • 6
  • 14
  • 30

3 Answers3

25

its var searchThis = document.getElementById('imgToFind').innerHTML;

to extract only text you can do:

element = document.getElementById('imgToFind');
var searchThis = element.textContent || element.innerText;
Shiv Deepak
  • 3,122
  • 5
  • 34
  • 49
  • 1
    THX! is there such a thing as `.text()` like in jquery? – Cyber Junkie Dec 05 '10 at 03:27
  • Thanks! I decided to use plain js because the google api doesn't use jquery. Thought I would do everything in one script. I just need a few simple functions. – Cyber Junkie Dec 05 '10 at 03:49
  • 1
    No, you don't need a parser to extract the text from a DOM element. You can use the element's `textContent` or `innerText` property as per my answer or traverse the DOM and amalgamate text from each text node encountered. It's not that hard and doesn't require jQuery. – Tim Down Dec 05 '10 at 15:43
  • @Tim: Thanks to enlight me. I dint know that. – Shiv Deepak Dec 05 '10 at 16:00
5

var searchThis = document.getElementById('imgToFind').innerHTML;

will grab the contents of the element :)

Damien-Wright
  • 7,296
  • 4
  • 27
  • 23
2

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 cases but for your purposes they may well be.

var el = document.getElementById("foo");
var text = el.textContent || el.innerText;
Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536