1

I am trying to avoid to repeat each time

$('.element1'),
$('.element1').html(),

in

myList = [
    {
        element: $('.element1'),
        text: element.html(),
        value: 'somevalue'
    },
    {
        element: $('.element2'),
        text: element.html(),
        value: 'somevalue'
    }
];


but actually it is not working, it shows me the eroor:
Uncaught ReferenceError: element is not defined

I need to define and keep everything only inside the "myList",
avoiding to define other external variables etc, and I would like to know how I can use something like this

I really appreciate any help

neoDev
  • 2,879
  • 3
  • 33
  • 66
  • jquery returns an object so you may have to use element : { $('.element1') }, (only guessing at this. –  Nov 19 '15 at 11:36

3 Answers3

0

You have to declare the variable before. Property/key of objects are not variable themselves in the current scope.

var element = $('.element1');
var element2 = $('.element2');

myList = [
    {
        element: element,
        text: element.html(),
        value: 'somevalue'
    },
    {
        element: element2,
        text: element2.html(),
        value: 'somevalue'
    }
];

Also check here for possible one time initialization of the object. This would not save you so much typing and code.

Self-references in object literal declarations

is not really clear why you want to avoid to repeat them and keep all of them in the object, of course saving the processing of jquery functions is a reason.

Community
  • 1
  • 1
AndreaBogazzi
  • 14,323
  • 3
  • 38
  • 63
  • I need to define and keep everything only inside the "myList", avoiding to define other external variables etc, and I would like to know how I can use something – neoDev Nov 19 '15 at 11:36
  • Also, it is a good practice to use a `$` prefix for variables which are jQuery objects. So, it is better to name them `$element` and `$element2`. – Yeldar Kurmangaliyev Nov 19 '15 at 11:36
  • I prefer to do not mess up with the dollar that for me is a php variable long before than a javascript jQuery object. – AndreaBogazzi Nov 19 '15 at 11:44
0

You want to separate your data from your logic a bit more, so that it can scale later

myList = [
    {
        element: '.element1',
        value: 'somevalue'
    },
    {
        element: '.element2',
        value: 'somevalue'
    }
];

myList.forEach(function(elem) {
   $(elem.element).html(elem.value)
});
Simon H
  • 20,332
  • 14
  • 71
  • 128
0
    myList = [
        {
            element: $('.element1'),
            value: 'somevalue'
        },
        {
            element: $('.element2'),
            value: 'somevalue'
        }

    ];
    for( var i in myList ) {
        myList[ i ]["text"] = myList[ i ][ "element" ].html();
    }
RiccardoC
  • 876
  • 5
  • 10