Search code examples
javascriptjquerypositionappendelement

How to get position of element after appending it to parent in javascript and jquery?


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.


Solution

  • 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/