0

I want add property in jquery object. I am trying to add property in jquery's context.I console the jquery object console.log($(this)), its look like an object. But when i am trying to amend the code is not working fiddle

$('ul').click(function(){
    $(this).myul={'date':'28 april'}
    console.log($(this))
})

enter image description here

Sanjeev Singh
  • 3,976
  • 3
  • 33
  • 38
Jitender
  • 7,593
  • 30
  • 104
  • 210

3 Answers3

2

You can add data in the data- attributes, in the HTML so an option would be to store:

$(this).data('myul', {'date':'28 april'});

the updated jsfiddle is here : http://jsfiddle.net/8juvcxqg/

filype
  • 8,034
  • 10
  • 40
  • 66
1

The problem is when you call $(this) every time a new jQuery wrapper will be created, so what every you added to the previous object won't be available in the new object.

You can test it using $(this) == $(this) which will return false.

The correct way will be is to use the data api

$('ul').click(function () {
    console.log('test', $(this) == $(this));//will be false since both the times different objects are returned

    console.group('Using cached object')
    var $this = $(this);//here we use a cached instance of the jQuery wrapper, this will work as long as you have a reference to $this - but is the wrong way
    $this.myul = {
        'date': '28 april'
    }
    console.log($this.myul);
    console.groupEnd()

    console.group('Using data api')
    $(this).data('myul', {
        'date': '28 april'
    });
    console.log($(this).data('myul'))
    console.groupEnd()
})

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

You don't even need jquery for this:

 this['myul'] = '"date":"28 april"';
 console.log($(this))

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125