2
\$\begingroup\$

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

Selectors:

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?

\$\endgroup\$
0

1 Answer 1

10
\$\begingroup\$

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().

$today.add($selected).html(date);
\$\endgroup\$

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.