jQuery… ready and selecting
To interact with HTML elements on a page, they first need to be loaded. jQuery has a built in event that allows us run our functions once the page is ready. Previously, when using javascript alone , we needed to wait until the entire page was loaded before we could run any scripts. So once the DOM is ready (even if all the page has not finished loading), we can run code!
$(document).ready(function() {
alert('Hello... your DOM is ready');
});
To make this easier, there is also a shortcut version, which is much cleaner.
$(function() { alert('Ready to go'); });
Moving on to selecting.
This enables the user to retrieve content from the document so it can be manipulated / used as desired. The selector used will return an array of objects that match the search criteria. Note, the array is not a set of DOM elements.
Basic Selectors
You will notice the the selectors are based on the CSS syntax. Some examples include:
- tagname: finds all elements of that tag i.e. p, h1,h3, ul
- #identifier: finds all with the specific ID
- .classname: finds all with the className
- tag.className: get elements of that tag, that have specific classname
- tag#id.className: get the tag element that has the ID and class value
So how could we code this using jQuery? Here are some examples:
Getting all the h1 tags in jQuery
$('h1');
Getting the tag with id “myList”
$('#myList');
Getting all the list items (li) tags with class .blue
$('li.blue');
As you can see this syntax is much shorter and easier than javascript, where we would be using code such as:
document.getElementByTagName("p");
More complex selections
- selector, selector: finds all elements that match
- .class1.class2: finds all that have both classes applied
- parent > child: find all child elements that are direct children
- prev + next: find all next elements that are next to prev element
- prev ~ siblings: find all siblings that come after prev and match sibling selector
So this is a short introduction to the coding of jQuery and using selectors. Good luck!
Leave a Reply