Table of contents
jquery
include
<script src="jquery-3.5.1.min.js"></script>
searching the dom
find HTML elements of type 'div'
$('div')find element with id 'example'
$('#example')find elements with class 'example'
$('.example')find elements having attribute [data-example]
$('[data-example]')find input elements of type text
$('input[type=text]')find anchor elements having title attribute starting with 'example'
$('a[title^="example"]')find anchor elements having title attribute ending with 'example'
$('a[title$="example"]')filtering results by index
$('table tr:gt(0)')
$('table tr:eq(5)')
$('table tr:lt(9)')get an attribute from a html element
var url = $('#example').attr('href');getting the text contained by an element
var text = $('#example').text();finding elements containing specified text
$("div:contains('partial match')")finding elements with contained text matching exactly
$('#example').filter(function() { return $.text([this]) === 'exact match'; });select children of a jquery match
$('[selector]').children('[selector]');iterate selector results
$('a').each(function() {
console.log('link:' + $(this).attr('href'));
});only do something if the selector has matches
if ($(selector).length ) {documentation on selectors
http://api.jquery.com/category/selectors/
general
accessing the matching element from within function
$('[selector]').click(function() {
var selected = $(this);
alert('clicked: ' + selected.text());
})accessing the parent of a node
node.parent()
manipulating the page
visibility
getting current visibility
var visible = $(this).is(":visible")show an element
$('[selector]').show();hide an element
$('[selector]').hide();toggle between visible and invisible
$('[selector]').toggle();visibility based on boolean value
element.toggle(visible)
CSS
apply css
$('[selector]').css('width', '250px');getting current class
$('[selector]').attr('class');add css class to dom element(s)
$('[selector]').addClass("example");remove css class from dom element(s)
$("[selector]").removeClass("example");toggle between 2 classes
$(this).toggleClass("[A] [B]");html
get text contained in element
$('[selector]').text();get contained html
$('[selector]').html();set inner html (replace)
$('[selector]').html('');prepend html
$('[selector]').prepend('');append html
$('[selector]').append('');forms
getting the value of an input
$('[selector]').val();setting the value of an input
$('[selector]').val('new value');check checkbox
$('[selector]').prop('checked', true);checkbox is checked?
$('[selector]').is(":checked")events
mouse
click on element(s) with selector
$('[selector]').click();assign mouse click listener
$('[selector]').click(function() {click listener but prevent default action (e.g. open link)
$("[selector]").click (function (event) {
$(this).hide();
event.preventDefault();
return false;
});call function on mouse enter
$(selector).mouseenter(function() {change events
change event: fired when input loses focus
$("[selector]").change(function() {...});change event: fired when mouse or keyboard modifies value, before writeback
$('[selector]').on('input', function() {example: allow only numbers in input field
$('[selector]').on('input', function() {
var old = $(this).val();
var number = old.replace(/[^0-9]*/g, '');
$(this).val(number);
}key bindings
key up event
$(document).keyup(function(e){
if (e.which == 27){
// do something
}
});binding a key with ctrl + alt
$(document).bind('keydown', function(event) {
if(event.altKey && event.ctrlKey) {
var key = String.fromCharCode(event.which).toLowerCase();javascript key codes
https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
dynamic elements
register event for element that doesn't exist yet
<div id="dynamic">
</div>
<script>
$('#dynamic').on('contextmenu', 'span', function(e) {
$(this).html(new Date().getTime());
e.preventDefault();
});
document.getElementById('dynamic').innerHTML = '<span>timestamp</span>';
</script>AJAX
load the results of an ajax call into a dom element
$("#someelement").load('http://example.com');ajax call with parameters
$.ajax({
url:"/path/to/page",
cache:false,
data:{foo:'bar',bas:'baz'}
}).done(function(result){
$('#foo').html(result)
});do HTTP POST with ajax
$.post("/path/to/page",
{
param1: "value1",
param2: "value2"
},
function(data, status){
$('body').html('<h1>Success!</h1>');
}
);register events on a top level element, so that they don't disappear when the content is replaced with ajax
.on( events [, selector ] [, data ], handler )
links for the "on" selector
http://api.jquery.com/on/
https://api.jquery.com/contains-selector/
examples
filtering rows in a table
function filter_table(selector, predicate) {
$(selector).find('tr').each(function() {
tr = $(this)
tr.toggle(predicate(tr));
})
}
filter_table('table', function(tr) {
return tr.hasClass('odd')
})sorting rows in a table
function sortTable(table, tr, comparator) {
var root = $(table)
var rows = root.find(tr)
var sorted = rows.toArray().sort(comparator)
rows.remove()
sorted.forEach(function(row){
root.append(row)
})
}
$('#mytable th').click(function() {
column = $(this).index()
sortTable('#mytable', 'tr:gt(0)', function(rowA, rowB) {
aText = $(rowA).find("td").eq(column).text()
bText = $(rowB).find("td").eq(column).text()
return aText.localeCompare(bText)
})
})references
API
https://api.jquery.com/