[jQuery] Applying .html and .css at the same time

Hi,

Is there any technical or practical difference between the following two code?

$('#error').html('Please enter all the details.');
$('#error').css('display', 'block');
$('#error').html('Please enter all the details.').css('display', 'block');

I had been using the first one until I realized the second one works too, which has less total code.

Are they the same or is there any reason I shouldn’t use the second option?

Thanks for any ideas.

Quite the opposite – in the first variant, you’re inefficiently querying the DOM twice and create two jQuery objects, where in the second you’re creating only one. Chainability is a very important feature of jQuery, and where you can’t chain those methods directly (e.g. because the CSS has to applied later at some point), one should cache the resulting object like e.g.

$error = $('#error').html('Please enter all the details.')

// Then, later
if (someErrorOccurred) {
  $error.css('display', 'block')
}
1 Like

Ok, what about:

if (someErrorOccurred) {
    $('#error').html('Please enter all the details.').css('display', 'block');
}

I mean, is there a reason I shouldn’t use the above assuming that’s the only line the error element will be used.

EDIT: Sorry, I guess I got you wrong. Ignore my above message please.

Yes, if you can chain them all directly, that’s even better of course. :-)

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.