Search code examples
javascriptjquerycodemirror

javascript/jquery why does taken string not hold as a variable?


i try to get the "name" attribute from an element and use that string to call a already existing variable.

thats the html (the li's are function's target):::

<ul name="editor">
    <li><a href="#">Politics</a></li>
    <li><a href="#">Finance</a></li>
</ul>

getting name and use it on function "getCursor":::THIS DOES NOT WORK, WHY

var messa = $(item).parent().attr("name"); //getting name which is "editor"
start_cursor = messa.getCursor()

atm it only works if i "hardcode" the variable like this:

start_cursor = editor.getCursor()

"editor" is predefined like this (Codemirror):

var editor = CodeMirror.fromTextArea(document.getElementById("code"), 
{mode: "javascript"});

i want to make it dynamically by getting the stringname from ul.

thanks for your time and wisdom


Solution

  • To switch from a string to something defined in javascript, try

    objectTheVarIsDefinedIn[nameOfVariable]
    

    In this case I'm not sure which object/scope/function you used, I guess the general scope which would be

    window[messa].getCursor();
    

    or maybe you used a function, and you're still on the same level:

    this[messa].getCursor();