Ryan Smith
Ryan Smith

Reputation: 509

JQuery - Get css property within selector

I'm trying to set a custom attribute to the target element's CSS property (font-size). How do I access the css from within a selector like:

$('.font-900').attr('data-resfont', <font-size here>);

I tried:

$('.font-900').attr('data-resfont', this.css('font-size'));

I'm guessing this will not work as 'this' refers to the attr function. My next step was:

$('.font-900').attr('data-resfont', this.target.css('font-size'));

This doesn't seem to work either. I think I'm missing something simple.

Upvotes: 0

Views: 441

Answers (2)

anazimok
anazimok

Reputation: 1759

There are multiple ways of doing this:

  • Iterate over every element that matches:
$('.font-900').each(function() {
    $(this).attr('data-resfont', $(this).attr('font-size'))
});
  • Create a variable assignment:
var e = $('.font-900');
e.css('data-resfont', e.attr('font-size');
  • Use function to set the attribute
$(".font-900").attr('data-resfont', function () {
   return this.style.fontSize;
});

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191729

You can use a function as the second argument to .attr which is iterated over each element in the collection (you cannot do this with .data or I would have suggested using that).

$(".font-900").attr('data-resfont', function () {
    return this.style.fontSize;
});

Upvotes: 0

Related Questions