jQuery Foundations: Content Filter Selectors
jQuery Foundations: Element Manipulation
•
We can both set and get an attribute value by using the
attr()
method.
// link is assigned the href attribute of the first <a> tag
var link = $("a").
attr
(
"href"
)
;
// change all links in the page to
$("a").
attr(
"href",""
)
; //note: operates on ALL <a>, no need for loop
// change the class for all images on the page to fancy
$("img").
attr(
"class","fancy"
)
; //ditto
jQuery Foundations: Element Manipulation
•
The
prop()
method is the preferred way to retrieve and set the value
of a property.
<input class="
meh
" type="checkbox" checked="checked">
var theBox = $(".meh");
theBox.
prop(
"checked"
)
; // evaluates to TRUE
Note: theBox is an array, so why is the syntax not
theBox[0].prop(“checked”);

4
jQuery Foundations: Changing CSS
•
jQuery provides the extremely intuitive
css()
method.
var color = $("#element")
.css(
"background-color"
)
; // get the color
$("#element").
css(
"background-color", "red"
)
; // set color to red
,
Same rule as before:
–
When setting a value, set it for all elements selected
–
When retrieving a value, retrieve value associated with first element in result set
jQuery Event Handling
Event Handling in jQuery
,
Just like JavaScript, jQuery supports creation and management of
listeners/handlers for JavaScript events.
,
While pure JavaScript uses the
addEventListener()
method, jQuery
has
on()
and
off()
methods as well as shortcut methods to attach
events.
Event Handling in jQuery: Binding and Unbinding
Events

5
Event Handling in jQuery: Page Loading
$(document).
ready
(
function()
{
// set up listeners knowing page loads before this runs
$("#example").click
(
function ()
{
$("#message").html("you clicked");
}
)
;
}
)
;
Or the even simpler
$(function () {
...
}
)
;
jQuery DOM Manipulation
DOM Manipulation: Creating Nodes
// pure JavaScript way
var jsLink = document.createElement("a");
jsLink.href = "";
jsLink.innerHTML = "Visit Us";
jsLink.title = "JS";
// jQuery version 1
var link1 = $('<a href=""
title="jQuery">Visit Us</a>');
DOM Manipulation: Creating Nodes
// jQuery version 2
var link2 = $('<a></a>');
link2.attr("href","");
link2.attr("title","jQuery verbose");
link2.html("Visit Us");
// jQuery version 3
$('<a>', {
href: '',
title: 'jQuery',
text: 'Visit Us'
});

6
DOM Manipulation: Adding DOM Elements
DOM Manipulation
•
Wrap all elements matched by a selector within a new element using
wrap().


You've reached the end of your free preview.
Want to read all 12 pages?
- Fall '09
- KUNZ