Leen
Leen

Reputation: 39

undefined after declaring the variable

<!DOCTYPE html>
<html>

<head>
  <meta charset=utf-8 />
  <title>moving word</title>
</head>

<body>
  <p id="word">w3resource</p>
</body>

</html>

<script type="text/javascript" src="five.js"></script>





function MovingLetters() {
  var text = document.getElementById("word").value;
  var len = text.length;
  var lastletter = text.charAt(len-1);
  text = text.substring(0,len-1);
  text = lastletter + text;
}

MovingLetters();

$(function() {
  setInterval(MovingLetters, 1000);
});

Console gives me :

Cannot read property 'length' of undefined

No idea why it is undefined because I defined it 2 lines before that one while that one reflects to a <p> in the html code that runs before the js script runs. Can someone help?

Upvotes: 0

Views: 41

Answers (2)

Get Off My Lawn
Get Off My Lawn

Reputation: 36351

using value is for input elements, you should use textContent, innerText or if you want the html innerHTML:

var text = document.getElementById("word").textContent;

function MovingLetters() {
  var word = document.getElementById("word")
  var text = word.textContent;
  var len = text.length;
  var lastletter = text.charAt(len - 1);
  text = text.substring(0, len - 1);
  text = lastletter + text;
  word.textContent = text
}

MovingLetters();
setInterval(MovingLetters, 1000);
<p id="word">w3resource</p>

Upvotes: 2

Gorgamite
Gorgamite

Reputation: 237

You dont't want the value you want what's called innerHTML. you can achieve this by doing document.getElementById("word").innerHTML.length.

Upvotes: 0

Related Questions