2

I'm trying to retrieve the value (example below is 7) of a paragraph element from my HTML doc, then reference this value in an external javascript file and use it as a variable.

HTML:

<div id="container" class="container">

        <p id="speedTransition">7</p>

    </div>

I then populate the js using .innerHTML calls so I can reference the id but...

Javascript Attempt 1:

var b   = Number(speedTransition);

Javascript Attempt 2:

var b   = document.getElementById("speedTransition").value = Number(speedTransition);

All console calls referencing "speedTransition" come back undefined and thus speedTrans returns NaN.

console.log("speedTransition = " + container.speedTransition);
console.log("speedTrans = " + speedTrans);

Any help massively appreciated! Thanks guys! First post!

:)

Ewan Brock
  • 23
  • 1
  • 3

2 Answers2

8

You were missing textContent. This will get you the text of the p elemeant

var p = document.getElementById('speedTransition');
var text = p.textContent;
var number = Number(text);
document.write(number);
<div id="container" class="container">

  <p id="speedTransition">7</p>

</div>
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
  • innerHTML iwll give him the HTML of the p element - if there is nothing else in there, the text. To get the text regardless, textContent or innerText – mplungjan Jun 11 '15 at 11:37
  • Wow, just casting to number. And I thought you needed `parseInt` or `parseFloat`. – GolezTrol Jun 11 '15 at 11:37
  • You could even do `var number = +text` – mplungjan Jun 11 '15 at 11:38
  • @GolezTrol, are you saying that sarcastically? Am I doing something wrong? – AmmarCSE Jun 11 '15 at 11:38
  • @mplungjan, you are right. Thanks for the tip. updated my answer – AmmarCSE Jun 11 '15 at 11:39
  • 1
    Yeah, but add the textContent if no innerText – mplungjan Jun 11 '15 at 11:39
  • @AmmarCSE No, not at all. I think this is nicer, but I didn't know this. I would have done it the way Ajay Chaudhary suggested in his answer. – GolezTrol Jun 11 '15 at 11:39
  • @mplungjan, you said 'but add the textContent if no innerText'. Do you mean if the text was hidden then textContent would have a value while innerText doesnt? – AmmarCSE Jun 11 '15 at 11:43
  • No. innerText is [not supported by all browsers](http://stackoverflow.com/questions/1359469/innertext-works-in-ie-but-not-in-firefox), most of the ones that do not support it, support textContent – mplungjan Jun 11 '15 at 11:48
  • 1
    @mplungjan, thanks for your awesome and helpful information. Ive learned more than the OP answering this question :). Thats what I love about SO – AmmarCSE Jun 11 '15 at 11:50
  • Yeah, thanks guys - this works! Tried out textContent too. Perfect! – Ewan Brock Jun 11 '15 at 13:17
2

try this

var b = parseInt(document.getElementById("speedTransition").innerHTML,10);
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Ajay Chaudhary
  • 298
  • 2
  • 14