splucena
splucena

Reputation: 159

How to get innerText in javascript when elements are supplied in runtime?

I'm trying to get the innerText of an element but it's returning undefined.

code:

 <td id="some-id"><obs conceptId="3156" style="textarea"/>(this one here inserts the span element)</td>

generated html during runtime:

 <td id="some-id"><span class="value">14</span></td>

I have tried using document.getElementById("some-id").innerText result was undefined. I have tried using document.getElementById("some-id").innerHTML result was <span class="value">14</span>. I would like to get the value 14.

Upvotes: 1

Views: 4469

Answers (3)

Bhavik
Bhavik

Reputation: 4894

Demo Fiddle
Javascript

var td = document.getElementById('some-id');
alert(td.getElementsByTagName('span')[0].innerHTML);  

And your question about innerText it will work only in IE, as per I know Firefox and Chrome uses textContent

Fiddle with textContent

Hope it helps..!!

Upvotes: 2

Nijanthan
Nijanthan

Reputation: 127

Try this,

document.getElementsByTagName("span")[0].innerHTML

Upvotes: -1

jeoj
jeoj

Reputation: 653

I think I'm targeting the span that's why it's returning undefined. Span is inserted during runtime how can I go one step deeper to get the value 14.

Take a look at this: http://jsfiddle.net/8sr2D/1/

If

<table>
  <td id="some-id"><span class="value">14</span></td>
</table>

will always be the situation, then I think:

function getValueForTd(id) {
    var element = document.getElementById(id);
    var span = element.childNodes[0];

    if(span !== undefined) {
        var value = span.innerText;
        return value;
    }   

    return false;
}

should get you your value.

Upvotes: 1

Related Questions