2

I need to set an element's background color from an attribute. At the current moment I am trying:

$( '[myAttr]' ).css( 'background-color', $( this ).attr( 'myAttr' ) );

but $( this ).attr( 'myAttr' ) is returning undefined.

Is there a way to do this?

2
  • 2
    Post your html and script. this probably isn't referring to what you think it is referring to. Commented Jan 10, 2016 at 18:10
  • Provide the code snippet as it is yet not clear what this is referring. Commented Jan 10, 2016 at 18:13

3 Answers 3

1

In your example, this doesn't refer to the [myAttr] element because there is no scope.

You could pass an anonymous function (so that you have access to this), and return the attribute value:

$('[myAttr]').css('background-color', function () {
  return $(this).attr('myAttr');
});
Sign up to request clarification or add additional context in comments.

Comments

0

this is not relevant outside of a callback. Do something like this...

$('[myAttr]']).each(function() {
  $(this).css('background-color', $(this).attr('myAttr'))
})

Comments

0

this probably isn't referring the element. Try like below.

var elm = $('[myAttr]');
elm.css('background-color', elm.attr('myAttr'));

Comments

Your Answer

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