8

My colleague uses this code to show an element:

$('selector here').attr('style','display:inline-block');

I normally use this:

$('selector here').css('display','inline-block');

I know inline CSS using the style attribute is a bad practice, but other than that, does any of these two lines result in a higher-precedence CSS, or are these two lines completely identicaly from the point of view of how the element will look like?

I was assuming that .css() may have a lower precedence because inline CSS has a bigger priority.

4
  • As an aside to your question, neither are ideal. You should use show() instead Commented May 18, 2017 at 10:20
  • Why show() is better? Commented May 18, 2017 at 10:21
  • 1
    Because it completely decouples the CSS from the JS code. Commented May 18, 2017 at 10:22
  • 1
    When the element has display:none in the css, show() will add display:block to the style attribute of the element as you can see in this fiddle: jsfiddle.net/vem5qL2c/1 Commented May 18, 2017 at 11:25

1 Answer 1

14

Both add the style attribute to your element. I'd say the only difference is the readability of your code when you set multiple CSS attributes at once. Other than that, css() adds style, and only replaces if already exists. By using attr('style', ...) you replace the whole style attribute every time.

Let's say you have an element as below:

<div class='element' style='color:red'>test</div>

When you use $('.element').attr('style', 'display:none') this would result in:

<div class='element' style='display:none'>test</div>

When you'd use $(.element').css('display', 'none') this would result in:

<div class='element' style='color:red;display:none'>test</div>.

Using css() also allows you to set multiple style attributes while keeping your code readable:

$('.element').css({
    color: 'red',
    textDecoration: 'underline',
    // etc.
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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