Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript get html or text from div

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.

like image 270
Cyber Junkie Avatar asked Dec 05 '10 03:12

Cyber Junkie


People also ask

What is textContent in JavaScript?

The textContent is the DOM property that is used to set text content for the HTML element or get the text content written inside that element. If you set the text using textContent for an element, then the other child elements will be removed and only this text will be added in that element.

How do I get text in HTML?

Use the textContent property to get the text of an html element, e.g. const text = box. textContent . The textContent property returns the text content of the element and its descendants. If the element is empty, an empty string is returned.

What is document getElementById () innerHTML in JavaScript?

The easiest way to modify the content of an HTML element is by using the innerHTML property. To change the content of an HTML element, use this syntax: document.getElementById(id).innerHTML = new HTML.

How do I get all elements of tag div inside HTML?

document. getElementsByTagName("div") will return all divs in the document.


1 Answers

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

to extract only text you can do:

element = document.getElementById('imgToFind');
var searchThis = element.textContent || element.innerText;
like image 108
Shiv Deepak Avatar answered Oct 18 '22 04:10

Shiv Deepak