spacer in my experience
 
« prev
Using Variables in jQuery Selectors
March 21, 2011 3:05 PM


Sometimes you need a grab an object in jQuery using a variable name, this is pretty easy to do and you can get pretty stupid with it. First an easy one...

var foo = "some_div_id";
$('#' + foo).click(function() {
	alert("hey");
})

That will make a div with an id of 'some_div_id' alert the word "hey" when you click it. Now a stupid one...

$(".some_clicky_thing").dblclick(function() {
    $('#item_'
      + this.id.substr(this.id.length-1)
      + ' .section_header a.toggler')
    .trigger('click');
});

When "some_clicky_thing" is double clicked, that triggers the click event on an anchor, with the class of "toggler", inside of an html element with the class "section_header", inside of an html element who's id is a concatenated string of a constant and the currently operated-on-object's id's last character (in this case a number). *cough*

jQuery selectors are just strings that are evaluated, so feel free to generate a string following basic Javascript rules and use it in jQuery selectors. But, be careful. It's easy to make a selector that's really supid. :D




 
 
 

 
gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.