0

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.

2 Answers 2

1

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

That's a perfect answer but someone beat you to the solution I was looking for. Its only fair to accept their answer. I'd vote you up if I could!
Wjouldn't that be .each instead of .forEach?
0

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;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.