Luis Gallego
Luis Gallego

Reputation: 85

$(".class").width($(this)...) not working

I have a lot of divs with, let's say, the .class class. And I need to assign them a width based on an specific route

$(".class").width($(this).parent().next().find("code").width())

But, for some reason, it doesn't work with $(this) but it does when I do this:

$(".class").width($(".class").parent().next().find("code").width())

but obviously only for the first one. Any clue?

Upvotes: 2

Views: 151

Answers (3)

dfsq
dfsq

Reputation: 193291

The way you are calling these functions, there is no reason why this should point to each individual .class elements. You are in global context (of whatever), but not in the context of .class DOMElement.

You can use each method instead:

$(".class").each(function() {
    $(this).width($(this).parent().next().find("code").width());
});

or width method providing a function as a setter:

$(".class").width(function() {
    return $(this).parent().next().find("code").width();
});

Both methods will loop through every element in collection $('.class') and invoke callback functions in the context of every element.

Upvotes: 0

War10ck
War10ck

Reputation: 12508

Since classes are meant to be used on multiple elements, your jQuery selector is probably returning a set of elements rather than a single element. Additional jQuery operations such as .width() on a set of matched elements are only executed on the first match. Therefore you'll need to iterate over the matched set of elements in order to complete the function for each match.

$('.class').each(function (idx, elem) {
    // Returns the width
    // Not sure what the intention is here. Assign to variable maybe?
    return $(elem).parent().next().find('code').width();
});

Upvotes: 1

A. Wolff
A. Wolff

Reputation: 74420

jQuery width() method accepts a function:

A function returning the width to set. Receives the index position of the element in the set and the old width as arguments. Within the function, this refers to the current element in the set.

$(".class").width(function () {
    return $(this).parent().next().find("code").width()
});

Upvotes: 7

Related Questions