0

I am attempting to access an object with a dynamic key that is obtained from a list item on click. Each list item has a class that matches a key within the object. For some reason is get "undefined". Here is the fiddle http://jsfiddle.net/defmetalhead/sFLGA/

 $(function() {
    var a = 1;
    var b = 2;
    var c = 3;
    var d = 4;
    var e = 5;
    $('.menu li').on('click', function() {
        var liClass = $(this).attr('class');
        console.log(liClass);
        var someObject = {
            "a": a,
            "b": b,
            "c": c,
            "d": d,
            "e": e
        }
        console.log(someObject.a);        //THIS WORKS FINE
        console.log(someObject.liClass); //WHY DOESN'T THIS WORK
    });
});

Here is the HTML

<ul class="menu">
    <li class="a">First</li>
    <li class="b">Second</li>
    <li class="c">Third</li>
    <li class="d">Fourth</li>
    <li class="e">Fifth</li>
</ul>
1

2 Answers 2

4

liClass is not property of someObject. Do a plain console.log(liClass);

Sign up to request clarification or add additional context in comments.

1 Comment

liClass can be equal to "a" for instance. if the user clicks the first list item. So clicking the first list item should result in someObject.a
1

You have to do someObject[liClass]. someObject.liClass really means someObject["liClass"].

1 Comment

great, much appreciated. Need to work more often with objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.