kype
kype

Reputation: 595

Extract text in <span> class

I have the following javascript code designed to extract certain text from a webpage.

document.getElementById('availability').innerHTML

The problem is it extracts the span code as well. This is the output that i get

<span class="a-size-medium a-color-success">

        Only 14 left in stock.




</span>

However what i actually want to extract is

Only 14 left in stock.

This is the partial source code of the webpage im trying to extract data off.

<div id="availability" class="a-section a-spacing-none">   
<span class="a-size-medium a-color-success">       
        Only 14 left in stock.        
</span></div>

I know i can manipulate the extracted data to get the result i want. However i want to know if theres any way via a javascript code i can achieve this? Thanks in advance for any help

Upvotes: 1

Views: 2926

Answers (4)

Ankit
Ankit

Reputation: 3183

Assuming that the is the first child of the :

document.getElementById('availability').firstChild().innerHTML();

Please see jsfiddle

Upvotes: -2

Wojciech Bednarski
Wojciech Bednarski

Reputation: 6373

I think the best idea here is to use jQuery.

$('#availability').text().trim();

If you really need to use plain JavaScript, then you need to use for most browsers:

document.getElementById('availability').innerText

and for Firefox:

document.getElementById('availability').textContent

Upvotes: 0

DhruvJoshi
DhruvJoshi

Reputation: 17126

You should be using Jquery in this age. however you can still use innerHTML property.

document.getElementById('availability').innerText

Upvotes: 1

Alex K.
Alex K.

Reputation: 175748

Assuming the <span> is the only child of the empty <div>:

var el = document.getElementById('availability');
var text = el.innerText || el.textContent;

Upvotes: 5

Related Questions