0
var t = 0, i = 0;
var letter = document.createElement('span')
letter.id = "x" + t + "x" + i;
letter.innerHTML = text[t];
highlight.appendChild(letter);
var position = $("#" + "x" + t + "x" + i).position();

This is the code and it keeps saying the letter is undefined.

My Name
  • 133
  • 7

1 Answers1

1

Under the assumption that highlight is an actual DOM Node (not undefined) and text has been defined previously, the most probable cause is executing the script before the DOM has loaded. Try putting your script at the bottom of your html just before the closing </body>-Tag.

Here is a fiddle with the working code: https://jsfiddle.net/n9xk85b7/

marvinhagemeister
  • 2,801
  • 1
  • 22
  • 27
  • var text = ["ab", "cde"]; var hightlight = document.getElementById('highlight'); var t = 0, i = 0; var letter = document.createElement('span') letter.id = t + "x" + i; letter.innerHTML = "asdfasdfasdfasdfasdfasdfasdf
    "; highlight.appendChild(letter); var letter = document.createElement('span') letter.id = t + "x" + i; letter.innerHTML = text[t]; highlight.appendChild(letter); var position = $("#" + t + "x" + i).position(); document.getElementById('result').innerHTML = "top: " + position.top + ", left: " + position.left;
    – My Name Apr 27 '16 at 19:09
  • when you see that a linebreak appears by another appended element it does not get the right top offset – My Name Apr 27 '16 at 19:10
  • I found that if I don't use append but innerhtml it works – My Name Apr 27 '16 at 22:12