0

I hope the title somewhat sums up what I am trying to achieve.

Let's say I have two variables:

var one = $('div.foo, div.faa, div.fee, span, a, .all-sorts-of-objects'),
    two = $('div.fii, div.foo, span, .all-sorts-of-objects-two');

And now, I want to check if objects contained within two are also contained within one. In other words, if there are any objects within both variables.

I need this so that I can set-up a non-overriding hover function (i.e. because I'm adding inline color-styles, I need to target my objects wisely). This is the logic I came up with: (note the if(one == two) which is essentially my question).

one.hover(function() {
    if(one == two) { // if there is one or more objects in both variables..
       $(this).css('color', 'red');
    } else {
       $(this).css('color', 'blue');
    } 
}, function() {
    // ...
});

I hope I have been clear enough. If not, please let me know and I will do my best to explain this better.

Thank you very much!

2 Answers 2

2

Here is a quick and dirty way to do it:

var one = $('div.foo, div.faa, div.fee, span, a, .all-sorts-of-objects').addClass('one');
var two = $('div.fii, div.foo, span, .all-sorts-of-objects-two').addClass('two');

one.hover(function() {
    if(one.hasClass('two')) {
       $(this.css('color', 'red');
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Hey, thanks a ton! In the end I took a different but similar path. Your idea got me started. Thanks!
0

In my book the cleanest way (apart from refactoring to avoid these duplicate selectors if possible) would be to use the merge and unique jQuery utilities, something like:

var $merged = $.merge(one, two);
var $unique = $.unique($merged.get());

The $unique now has the unique, or, if you like, distinct elements.

1 Comment

I would have gone this way, if (for whatever possible reason) the $unique object would have held all my elements without breaking/splitting them. Somehow, $unique echoed parts of my elements only, such as "div#era-blocks-container" and nothing else. Either way, thanks for this!

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.