Simon
Simon

Reputation: 8349

Using the this keyword with jQuery selectors

Can someone please help me with the syntax of using the jQuery this keyword?

Here is my code that works:

var obj = jQuery.parseJSON(data);

$('.example_infobox1').addClass(obj.gridlayout);
$('.example_infobox1 .info-box').addClass(obj.boxcolor);    
$('.example_infobox1 .info-box-icon').addClass(obj.iconcolor);
$('.example_infobox1 i').addClass(obj.icon);
$('.example_infobox1 .info-box-text').html(obj.text);
$('.example_infobox1 .info-box-number').html(obj.number);

Here is the code that I am working on:

var obj = jQuery.parseJSON(data);

$('.example_infobox1')
{
    $(this).addClass(obj.gridlayout);
    $('.info-box', this).addClass(obj.boxcolor);    
    $('.info-box-icon', this).addClass(obj.iconcolor);
    $('i', this).addClass(obj.icon);
    $('.info-box-text', this).html(obj.text);
    $('.info-box-number', this).html(obj.number);
}   

I am not getting any errors in the console, however the html content is not being correctly formatted.

Thanks

Upvotes: 3

Views: 663

Answers (3)

Sumit Kumar
Sumit Kumar

Reputation: 404

this points to current object in jquery and it gives an error only when syntax is wrong. your should try this.

$(this).find('.info-box').addClass(obj.boxcolor); or $('.example_infobox1 > div[class = ".info-box"]').addClass(obj.boxcolor);

or

$(".example_infobox1 ").children(".info-box").addClass( "obj.boxcolor");

Upvotes: 0

Stuart Wagner
Stuart Wagner

Reputation: 2067

I think a variable would be better in this case.

var box = $('.example_infobox1');

box.addClass(obj.gridlayout);
$('.info-box', box).addClass(obj.boxcolor);    
$('.info-box-icon', box).addClass(obj.iconcolor);
$('i', box).addClass(obj.icon);
$('.info-box-text', box).html(obj.text);
$('.info-box-number', box).html(obj.number);

Upvotes: 2

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34244

Actually, that is the wrong usage of jQuery selector.

jQuery assignes current document object to this within this "selector".

http://jsfiddle.net/8rLdwr5w/1/
Take a look at this sample. Here the jQuery object contains the whole document and I can access external div using find method.

If you want the jQuery selection to be called once and then reused, follow Stuart Wagner's approach.

Upvotes: 0

Related Questions