JQuery
Selectors
- type:
$('table') - attribute:
$('[date="2015-04-21"]') - class:
$('.even') - id:
$('#main')
Filters
$('tr:eq(0)')finds the first row in a table$('tr:gt(0)')finds all rows after the first:evenfinds all even-numbered elements in a selection:oddodd-numbered elements:lastlast element:emptyelements that have no children:focusthe focused element:not(selection)elements that don't match selection:contains(text)element that contain certain text- input field selectors:
:hidden,:text,:checkbox,:password
Combinations
$('tr.even')Rows with class 'even'$('#tasks tr:first')The first row of a table with id 'tasks'$('#tasks').find('tr:first')Same thing$('tr:first', '#tasks')Same thing; second argument specifies DOM sub-tree to search$('section:eq(1) table tr:last td')All table cells in the last row of all tables in the second section$('select[name="category"] > option')All option elements that direct children of a particular select
Traversals
$('some selector').siblings()all siblings of the selected elements$('some selector').siblings('td')the siblings of the selected elements that are td's.next(),.prev(),.parent(),.closest(),.last().parents('.funky')any parents of the selected elements that are of class 'funky'.andSelf()make sure the selected element(s) is included
Manipulation
.addClass('even'),.removeClass(...),.toggleClass(...).append('...some html...')add as last child of selected element.prepend(...),.after(...),.before(...).remove(...),.replaceWith(...),.before(...)$('select').val()get the value of the select element$('select').val('AM')set the value of the select element.html(),.text(),.attr()
Events
.click(),.dblclick(),.hover(),.mousedown(),.mouseup().keypress(),.keydown(),.blur(),.change(),.focus()- suppress default behavior of link, button, etc:
$('#myButton').click( function(e){
e.preventDefault();
// do something else
});
Example
HTML
<html><head><title>Button Magic</title>
<link rel='stylesheet' type='text/css' href='stylesheet.css'/>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript' src='script.js'></script>
</head><body>
<div><br/><strong>Click Me!</strong></div>
</body>
</html>
stylesheet.css
div {
height: 60px;
width: 100px;
border-radius: 5px;
background-color: #69D2E7;
text-align: center;
color: #FFFFFF;
font-family: Verdana, Arial, Sans-Serif;
opacity: 0.5;
}
script.js
$(document).ready(function(){
$('div').mouseenter(function(){
$('div').fadeTo('fast', 1.0);
});
$('div').mouseleave(function(){
$('div').fadeTo('fast', 0.5);
});
});
To Do List Example
HTML
<h2>To Do</h2>
<form name="checkListForm">
<input type="text" name="checkListItem"/>
</form>
<div id="button">Add!</div>
<br/>
<div id="list"></div>
script.js
$(document).ready(function(){
$('#button').click(function(){
var toAdd = $('input[name=checkListItem]').val();
$('#list').append('<div class="item">' + toAdd + '</div>');
});
$(document).on('click', '.item', function(){
$(this).remove()
});
});