Jitender
Jitender

Reputation: 7971

Add custom object in jquery's object

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

Upvotes: 0

Views: 426

Answers (3)

Milind Anantwar
Milind Anantwar

Reputation: 82241

You don't even need jquery for this:

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

Working Demo

Upvotes: 0

filype
filype

Reputation: 8380

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/

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388326

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

Upvotes: 1

Related Questions