Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does brackets and parentheses after jquery selector mean?

I ran into this line of code and I can't figure out what it means:

$("#theAppContainer")[s > u ? "addClass" : "removeClass"]("something");

I understand the first part is selecting the element called theAppContainer and the second part evaluates to "addClass" if s > u, but I can't figure out what this line of code does overall.

like image 208
user2403771 Avatar asked May 21 '13 02:05

user2403771


People also ask

What do square brackets mean in jQuery?

It means a table row who has an id that starts with "message": $('tr // a table row [id //having an id ^="message"]') // starting with 'message' http://api.jquery.com/category/selectors/attribute-selectors/ Follow this answer to receive notifications.

What is '$' in jQuery?

$ is pretty commonly used as a selector function in JS. In jQuery the $ function does much more than select things though. You can pass it a selector to get a collection of matching elements from the DOM. You can pass it a function to run when the document is ready (similar to body.

What do brackets mean in JavaScript?

Bracket notation is more expressive than dot notation because it allows a variable to specify all or part of the property name. This is possible because the JavaScript interpreter automatically converts the expression within the square brackets to a string, and then retrieves the corresponding property.

What do brackets mean in HTML?

You can see that HTML contains pieces enclosed in angle brackets (' < ' and ' > '), which are also known as the less-than and greater-than symbols. Each of these angle-bracket-enclosed pieces, called a tag, does not appear to the user, but rather gives information about the page's structure.


1 Answers

The bracket syntax gets the value of a property by name, and the parentheses call the function that is the value of that property. It’s equivalent to:

var container = $('#theAppContainer');

if(s > u) {
    container.addClass('something');
} else {
    container.removeClass('something');
}

Also, please never write code like that. =)

Also also, toggleClass takes a second switch argument that you can use instead:

$('#theAppContainer').toggleClass('something', s > u);
like image 168
Ry- Avatar answered Sep 23 '22 00:09

Ry-