To be good at JQuery, it is very important to understand and know how to select the HTML DOM elements. In this blog, I just wanted to provide some examples (more on the lines of a cheat sheet) of JQuery selectors which I use most often. I also wanted to document some of the methods that I use most of the times. I didn't want to go through JQuery documentation all the time. As I said, this list is not comprehensive but these are the items I use the most.
Selectors
Selectors
- $ is same as jquery.
- $('#id') selects the element with id = id
- $('p') selects all <p> elements
- $('p,a,span') selects all paragraphs, anchor and span tags
- $('ancestor descendants') selects all the descendants of ancestor. For ex. $('table tr') selects all tr tags in the table element. Descendants are children, grandchildren etc of ancestor.
- $('.classname') selects all elements which have class = classname
- $('.classA,.classB') selects all elements which have either classA or classB
- $('p.classA') selects only <p> tags which have class = classA
- $('a[title]') selects all <a> tags which have a title attribute
- $('a[title="somelink"]') selects all <a> tags which have title attribute = somelink
- $(':input') selects all input elements including input, textarea, select, button, image, radio, checkboxes etc. $('input') will select only <input> elements. Textarea is also input element but its written like <TextArea> that's why :input is handy.
- $('div:contains("internet")') selects all the div elements whose value contains the text "internet"
- $('tr:odd') and $('tr:even') selects all the odd and even rows respectively.
- $('tr:first-child') and $('tr:last-child') selects the first and the last row respectively
- $(input[value^="internet"]) selects all inputs whose value attribute STARTS with the word "internet"
- $(input[value$="internet"]) selects all inputs whose value attribute ENDS with the word "internet"
- $(input[value*="internet"]) selects all inputs whose value attribute CONTAINS the word "internet"
- $('input', $('#mainDivs')) will find all inputs inside the mainDivs element
- $('div:eq(0)', $('#mainDivs')) will find the first div inside the mainDivs element
- .each(function(index, Element)) - loops through each element. It also provides the index of the item being looped. The current item can be referenced by using $(this) or using $(Element) where Element is the input passed. Usually we dont need to use $(Element) as $(this) does the job. So mostly the usage of each is like .each(function(index)).
- .html() - gets the html.
- .html(htmlString) - sets the html of the referenced element by htmlString.
- .attr("id") - gets the value of the attribute id.
- .attr("id","5") - sets the value of attribute id to 5.
- .attr({"title":"some title", "alt":"5"}) - sets multiple attributes using JSON object. Text inside {} is a JSON object.
- $('.phone').append("<br/>Ph: 123-456-7890") will APPEND the phone number to all elements which have class phone.
- $('.phone').prepend("Ph: 123-456-7890<br/>") will PREPEND the phone number to all elements which have class phone.
- $('.phone').wrap("<div></div>") will WRAP the div around all elements which have class phone.
- $('.phone').unwrap() will UNWRAP the parent around all elements which have class phone.
- $('.classA').css("border", "2px red solid") will apply border style with value 2px red and solid on all elements which have class = classA
- $('.classA').css({"border":"2px red solid","font-size":"16px"}) will apply multiple styles (border and font-size) to elements with classA using JSON object
- val() - gets the value of the element
- val(str) - sets the value of the element to str
- $('#t1').addClass("classexample") - adds the class classexample to element id #t1
- $('#t1').removeClass("classexample") - removes the class classexample from element id #t1
- $('#t1').toggleClass("highlight") - toggles the class i.e if class is applied, it removes it, if its not there, it adds it
- $('#id').clone() - clones the id element
Events
- $('#id').click(function(){ // do something }) will register a click event to element with id = id
- $('#id').change(function(){ // do something }) change is mostly used for <select> elements. It gets fired everytime selection is changed. Inside the function $(this) will give you the changed value. change also works with textarea and input also.
- $('#id').mouseenter(function(){ // do something}) is for mouseenter
- $('#id').mouseleave(function(){ // do something}) is for mouseleave
- $('#id').bind("mousenter", mouseEnterFunc) - binds the mouseenter event to item with id = id.
- $('#id').bind("mouseenter mouseleave mouseup", bindingExample) - bind's main advantage is that it allows you to bind multiple events in a simple manner. Then in the bindingExample method, you can use e.type to see which event is called in case you want to do different things.
- $('#id').bind({mouseenter:funcenter, mouseleave:funcleave, mouseup:funcup}) - will do the same thing as above but in JSON object
- $('#id').unbind() - unbinds all the events associated with id
- $('#id').unbind("mouseenter") - unbinds only the event specified
- $('#id').delegate('input','keypress' function() { // do something }) - bind and delegate are similar. the only difference is that when you attach events through bind, any elements added through code or after load, the event will not get attached to these new elements. If you use delegate, it will keep on monitoring and even if new elements are added, it will attach the event handler. In this example, for anything under the context of id, a keypress event is attached to all inputs. When keypress happens, function will get called. You can use the undelegate function to get rid of event handlers.
- $('#id').hover(func1, func2) - func1 is mouseenter and func2 is mouseleave.
- $('#id').hover(func1) - func1 will be used as mouseenter and mouseleave. Its a good place to use toggleClass method.
- $('#id').toggle(func1, func2, callback) - when you click id, first func1 will get called, at 2nd click func2 will get called. In the end callback will be called. This is good place to add some class in func1 add a different class in func2 and then remove the classes in callback. 4th click will then again call func1.
- $('#id').toggle() - hides or shows the element. You can also provide a boolean for show and hide or duration and callback for it to fade out etc.
AJAX Functions
- $('#id').load() - loads HTML data from the server. It provides capabilities to get parts of html by providing selectors or if the page takes arguments, we can send the arguments as well using JSON object. It also provides a call back function after the load is completed.
- $.get(url,data,callback,type) - fires a get request. data is data sent to the server. callback contains the data returned from server apart from other arguments such as textStatus and jqXHR which is jquery XML Http Request object. type is the type of data server will return (HTML, XML, JSON)
- $.getJson(ur, data, callback) - similar to get with type = JSON.
- $.post(url,data,callback,type) - fires a post request. rest is same as get.
- $.ajax({//settings json object}) - the low level api. Load, Get, Post all of them ultimately fire ajax function. ajax function arguments can be provided in the form of a json object and it provides more control with what we want to do with ajax calls.
CSS Selectors
- #id word following after # is the id of the element to which css can be applied
- .class word following after . is the class of elements to which css can be applied
- Document.Ready is called when the page is loaded. i.e HTML DOM is loaded. It may mean that all images have not been loaded yet but DOM is loaded.
- keyword this represents the raw DOM object while $(this) represents the raw DOM object wrapped inside jquery. Therefore, $(this) has jquery methods available to it while this does not. this has access to raw properties though.
- CDN benefits - faster, cached, 99.9% uptime. Good for internet apps. For Intranet better to have your own copy.