6

Say I have a function that accepts multiple jQuery objects:

workWithThreeObjs($('.content'), $('h1'), $('input[type=button]')); 

I define my function like this:

function workWithThreeObjs(p, h1, buttons) { ... } 

Inside this function, I want to apply border to all of them like this

$(p, h1, buttons).css(...); 

How do I do that? Right now it only applies to p.

My function code does not control what is passed into it, so I cannot change the selectors used to create the arguments. I must operate only on the jQuery objects provided.

7
  • Google has only shown me duplicates which are different so not a duplicates. They talk about grouping selectors not objects. Commented Jun 3, 2015 at 18:38
  • 1
    @MuhammadUmer It is a duplicate, I've seen it many times, but "add" is such a common term it's hard to find on SO... Commented Jun 3, 2015 at 18:42
  • i agree with you @DenysSéguret . i have seen it many times too. Commented Jun 3, 2015 at 18:44
  • 1
    I stand corrected; I'm a little surprised by that (though I'm not sure why). Commented Jun 3, 2015 at 18:47
  • 1
    Or, possibly an even better option: How to combine two jQuery results Commented Jun 3, 2015 at 18:58

2 Answers 2

10

Assuming that you want to use variables

Use $.fn.add()

Create a new jQuery object with elements added to the set of matched elements.

var p = $('.content'), h1 = $('h1'), buttons = $('input[type=button]'); p.add(h1).add(buttons).css({}) 

DEMO

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

1 Comment

not sure why the discussion is continuing elsewhere, this is the answer. At least until someone finds the right duplicate to mark it with
2
var p = $('.content'), h1 = $('h1'), buttons = $('input[type=button]'); function workAnyNumberofObjects() { for(var i=0; i<arguments.length; i++){ arguments[i].css('border', '1px solid blue') } } workAnyNumberofObjects(p,h1,buttons); 

You should be able to use any number of selectors here

2 Comments

yes but i already have selectors deep in code, and they are specific based on some alogrithim. This example was meant to show what i wanted to do not how my code is.
Then give a better example of what you're doing to show your problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.