Posts Tagged ‘jQuery’
Selecting an object at a specific index with jQuery
July 6, 2010As you probably know, the jQuery selector returns all the matched elements as an array. But what if you needed to select only the third element in the returned elements list?
The code below will return only the 3rd element in the returned selected list
// get 3rd item as a jQuery object: $('div:eq(2)') // get 3rd item as a pure DOM object $('div')[2];
How to bind events in jQuery
I used to bind mouse events to dom elements using the .click() method like below:
$("a.button").click(function(){ alert("A button was clicked"); })
The problem with this technique is that everytime a new button is added to the dom, you need to re-apply the click behavior to it.
Fortunately, jQuery introduced the .live() method in version 1.3 which solves that issue. The .live() method will bind an event to any element matching the selector now or at any point in the future, so if you you add new buttons to the page dynamically, they will also be binded to the event.
Use:as follows:
$('a.button').live('click', function(){ alert("A button was clicked"); });
How to remove or empty elements in jQuery
Removing or emptying dom elements with jQuery
// Removes the element from the dom $('selector').remove() // Empties the element $('selector').empty();
Note that this will empty or remove every element matched by the selector, so if you have 25 divs with the class “article-content” and you do $(’div.article-content’).empty(); , It will empty the 25 divs selected.
How to select children or parent elements in jQuery
Selecting Child or parent elements in jQuery is quite simple and powerful:
// Selecting child elements $('selector').children('.class-name') // or any other selector like: $('selector').children('div span') // Selecting the parent element $('selector').parent()

