Skip to content

Instantly share code, notes, and snippets.

@clifgriffin
Last active December 20, 2015 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clifgriffin/6184402 to your computer and use it in GitHub Desktop.
Save clifgriffin/6184402 to your computer and use it in GitHub Desktop.
Two equally bad approaches to jQuery development (I think)
// I often find myself searching up the DOM tree with jQuery to access related items.
// Say, each item is in a li and I need to toggle other elements in that li.
// This usually takes the form of a blind man, counting floor tiles so he can find his way back,
// or similar. Either way, it feels like bad form and is probably very ineffienct.
// Solution A: Tag each relevant markup item with a particular ID attribute that is used to lookup related elements
jQuery("a.edit-todo-link").click(function(e) {
var todo_id = jQuery(this).attr('todo_id');
var parent_container = jQuery('li[todo_id=' + todo_id + ']');
parent_container.find('.edit-todo').css('display', 'inline');
parent_container.find('a.todo-title').hide();
e.preventDefault();
});
// Solution B: Search up tree using closest, etc
jQuery("a.edit-todo-link").click(function(e) {
var parent_container = jQuery(this).closest('li');
parent_container.find('.edit-todo').css('display', 'inline');
parent_container.find('a.todo-title').hide();
e.preventDefault();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment