Hey! I’ve finally started feeling comfortable using jQuery, so now I’m trying to improve the I write my code. Is there anyone who could help me make this code more efficient?
$("a.more_info").toggle(function(){
var itemid = $(this).parent().parent().parent().parent().attr('id');
var itemid_hash = "#" + itemid + " .details_exp";
var itemid_tog_more = "#" + itemid + " a.more_info"; $(itemid_tog_more).addClass("less_info").removeClass("more_info");
$(itemid_hash).fadeIn();
}, function () {
var itemid = $(this).parent().parent().parent().parent().attr('id');
var itemid_hash = "#" + itemid + " .details_exp";
var itemid_tog_less = "#" + itemid + " a.less_info";
$(itemid_tog_less).addClass("more_info").removeClass("less_info");
$(itemid_hash).fadeOut();
});
First, is there a way to go up four levels in the DOM without stacking up .parent() four times? Second, is there a better way to define the “itemid” and ” itemid_hash” variables so I don’t have to redefine them for the second half of the toggle function? The code is working great as is, but I just want to make sure I’ve doing things in the most correct way. Thanks!
Update 2: Working demo.
Update: For completeness, this is the HTML I’m referring to (only relevant part):
You can do like this:
There is no need to build the selectors manually. And I think
item_tog_lessactually refers to the currently clicked element right? Then you can just use$(this).If the box with the details always comes after the link (more precisely its parent, it looked like this) you can also do:
Reference:
find(),closest(),nextAll()p.s.: Nice site!