In my webpage I have two places where I need my JavaScript to write dates. How to do it in one go?


var $today = $('#today');
var $selected = $('#selected');

If I were to do this alternatively the easy way, I'd do:

$('#today, #selected').html(date);

But I kind of need to reuse my #selected jQuery object throughout my code.

The only solution I came up with so far is...

$([$today, $selected]).each(function(idx, obj){obj.html(date);});

Is there a better way?


I believe you would be better off combining the two jQuery objects using .add() rather than a comma in the selector. It's also more elegant than having to call .each().


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.