Skip to the content
- You can select by id: var my_element = $(‘#element_id_here’);
- You can also select a group of tags: var linksList = $(‘a’);
- To select elements by class name (and then hide them in this case): $(‘.submenu’).hide();
- Filter the elements you choose by the preceding ids or tags: $(‘#navBar a’) This will select the a tags that are inside the #navBar id. As a matter of fact, you can follow the CSS syntax to select elements this way. Other variations of this are:
- $(‘body > p’) – Chooses the p tags that are children of body
- $(‘h2 + div’) – Chooses the very next adjacent children right after the h2 tag
- $(‘img[alt]’) – Attribute selecting images (in this case only if they have the alt attribute on them)
- $(‘input[type=text]’) – Selecting all attributes that have are type=text
- $(‘a[href^=mailto:]’) & $(‘a[href$=.pdf]’) – Attribute selection using regular expressions
- Jquery filters: these are used to selectively choose further from a given group of selected items, based on certain criteria:
- $(‘tr:even’) – From all the list of tr’s, it will only select the ‘even’ elements, you can also use tr:odd as a variation
- $(‘a:not(.navButton)’); – Select elements that don’t match the criteria inside the not(), in this case select a tags that are not of class navButton
- $(‘li:has(a)’) – Finds elements that contain another element, in this case, find all the li that contain an ‘a’ tag
- $(‘a:contains(Click Me!)’) – Find elements that contain a specific piece of text, in this case, find ‘a’ tags that contain the “Click Me!” text inside
- $(‘div:hidden’).show(); – Find elements that are currently hidden (and in this case show them). This does not find elements with ‘visibility’ property, only takes in account the ‘display’ property. “:visible” will be the opposite of this.
- Caution about elements picked by Jquery selectors: the normal methods used in JavaScript won’t work, you will have to use the JQuery equivalents. For example:
- $(‘#banner’).innerHTML = ‘New text’; // won’t work
- $(‘#banner’).HTML(‘New text’); // Propietary Jquery to say innerHTML, this will work
- A note about looping through a set of elements selected through Jquery: the loop is already built-in, you don’t have to specify it. For instance:
- $(‘#slideshow img’).hide(); – The groups of images selected can be hidden without having to loop through them one at a time
- Chaining functions to an element, you can do this in JQuery, as long as the chain of functions are also JQuery functions as well:
- $(‘#popUp’).width(300).height(300).text(‘Hi!’).fadeIn(1000);