Search code examples
javascriptjqueryjquery-selectorssidebar

Check if two selectors elements exist and have the same value in jQuery


Consider this code:

if ( $('.sidebar-primary, .sidebar-secondary').css('float') === 'left' ) {

It gives me a true even if .sidebar-secondary does not even exist in the HTML. Why is that and how do I make this work even if the .sidebar-secondary sometimes does not exist?


Solution

  • As the jQuery documentation says:

    [.css()]Get the value of a style property for the first element in the set of matched elements or set one or more CSS properties for every matched element.

    So only the first element of the array is considered. You need something like:

    var every = Function.call.bind(Array.prototype.every);
    
    var isFloatLeft = every($('.sidebar-primary, .sidebar-secondary'), function(node) {
        return $(node).css('float') === 'left'
    });
    
    console(isFloatLeft);
    

    Unfortunately jQuery doesn't have any every methods, luckily JavaScript (ES5 specs) does: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/every

    Notice that is a kind of generic approach in case you need to check multiple elements. For only two you can just compare them directly:

    isFloatLeft = $('.sidebar-primary').css('float') === 'float' && 
                  $('.sidebar-secondary').css('float') === 'float;