0

Why doesnt the following apply the css rules to both elements?

var prevElem = $('<a href="#" class="'+ settings.prev +'" />').text('Prev');
var nextElem = $('<a href="#" class="'+ settings.next +'" />').text('Next');
container.append(prevElem, nextElem);
$(prevElem, nextElem).css('top', container.height()/2);

Its only applied to prevElem.

Please note that the dynamic elements have been added to the DOM (with their classes) so they are there.

1
  • Have you declared settings.next class?? Commented Aug 4, 2012 at 12:04

2 Answers 2

3

To do what you need, you must call add() method.

var prevElem = $('<a href="#" class="'+ settings.prev +'" />').text('Prev');
var nextElem = $('<a href="#" class="'+ settings.next +'" />').text('Next');

prevElem.add(nextElem).appendTo(container).css('top', container.height()/2);

Reason you can't join arrays by providing them as parameters to jQuery, is that there is simply no such API. And there shouldn't be because it would make it impossible to implement jQuery( selector [, context] ) which searches for elements within context. Check out $.add() for what you attempted to do.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Nikola, great explanation. Your get the answer.
2

Your code should be:

prevElem.add(nextElement).css('top', container.height()/2);

If you have a look at the documentation of jQuery you will see that you cannot create a jQuery object with two elements the way you tried. Read the documentation, there is no need to guess how it works.

Comments

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.