Search code examples
javascriptjquery

What is this jQuery doing?


I would call myself an intermediate jQuery developer, but I'm confused about what this line (from Twitter's Bootstrap) is doing:

$tip.find('.help-popover-title')[ $.type(title) == 'object' ? 'append' : 'html' ](title)

Specifically, the part between the square brackets. Can anybody explain it to me?


Solution

  • $tip // tip object
    .find('.help-popover-title') // find elements of this class
    
    // if the data inside the title variable is an object
    // use the append method otherwise use html method
    [$.type(title)  == 'object' ? 'append': 'html']  
    
    (title) // lastly, execute the selected function and pass in the title var
    

    The inner statement uses a ternary operator. It's basically a single line if..else statement

    x = 5;
    
    x === 5 ? true : false; // true
    x === 4 ? true: false; // false
    

    Since the selected method is inside the brackets, you can use a string to select a method It's equalvelent to:

    $tip['append'](title) === $tip.append(title)