There are a few functions that jQuery provides to add content to a web page.
jQuery | example | effect |
---|---|---|
.html() | alert(($’#errors’).html(‘Oops’)); | creates an alert with the message ‘Oops’ for an element with ID ‘errors’ |
.text() | $(‘#errors h2′).text(‘no errors found’); | will replace the text in an h2 block for an element with ID ‘errors’ |
.append() | $(‘#errors’).append(‘some errors found’); | will append the text to an element with ID ‘errors’ |
.prepend() | $(‘#errors’).prepend(‘some errors found’); | will prepend the text to an element with ID ‘errors’ |
.after() | $(‘#username’).after(‘User Name is required’); | will place the text after to an element (e.g. div) with ID ‘username’ |
.before() | $(‘#username’).before(‘User Name is required’); | will place the text before to an element (e.g. div) with ID ‘username’ |
.remove() | $(‘#popup’).remove(); | deletes an element |
.replaceWith() | $(‘#cartInfo’).replaceWith(‘Item added to cart.’); | replaces an element – note this could have also replaced an different tag (e.g. img) with the p tag |
.addClass() | $(‘a[href^=”http://”]‘).addClass(‘externalLink’); | adds a class called ‘externalLink’ to all external links |
.removeClass() | $(‘a[href^=”http://”]‘).removeClass(‘externalLink’); | removes a class called ‘externalLink’ to all external links |
.toggleClass() | $(‘a[href^=”http://”]‘).toggleClass(‘externalLink’); | adds a class to an element if it doesn’t already exist, or removes a class if it does exist |
css() | $(‘#main’).css(‘background-color’); | GET a CSS property from an element |
css() | $(‘body’).css(‘font-size’, ’200%’); | SET a CSS property element |
css() | $(‘body’).css({‘font-size’ : ’200%’ , ‘border’ : ’2px solid #FE0037′}); | SET more than one CSS properties using an object literal |
css() | (‘body’).css(‘font-size’,’200%’).css(‘border’,’2px solid #FE0037′); | SET more than one CSS properties using chaining (more efficient than 2 function calls) |
attr() | var imgFile = $(‘#banner img’).attr(‘src’); | returns the src property for first img tag inside another tag with ID of banner |
attr() | $(‘#banner img’).attr(‘src’, ‘images/newImg.png’); | change a tag’s (e.g. ‘src’) attribute |
removeAttr() | $(‘body’).removeAttr(‘bgColor’); | completely remove an attribute from a tag |
fadeOut() | $(‘img’).fadeOut(); | jQuery automagically loops and fades out each img element |
each() | $(‘img‘).each(function() { alert(‘hello’); }); | performs a series of actions on each element |
Anonymous Functions
Anonymous functions are functions with – you guessed it – no name. Here is an example of one. In this example we are looking for every anchor tag with an ID of extLinkList which starts with the substring ‘http://’:
1 2 3 4 |
|
Note the the use of $(this) to refer to an individual element in the list.
This page is a summary of information found in: JavaScript and jQuery: The Missing Manual, pp138-150