Skip to content

Instantly share code, notes, and snippets.

@garethredfern
Created October 9, 2012 06:41
Show Gist options
  • Select an option

  • Save garethredfern/3857014 to your computer and use it in GitHub Desktop.

Select an option

Save garethredfern/3857014 to your computer and use it in GitHub Desktop.
Selecting with jQuery
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Selecting jQuery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h1>Container One<h1>
</div>
<div class="container">
<h1>Container Two</h1>
<ul class="list">
<li>Item One</li>
<li>Item Two</li>
<li>Item Three</li>
<li>Item Four
<ul>
<li>Item Four a</li>
</ul>
</li>
<li>Item Five</li>
</div>
<script>
(function() {
$('.list').children('li').addClass('children'); // this selects only the children li of the .list
$('.list').find('li').addClass('descendant'); // this selects all the descendant li's of the .list
$('.list li').first('li').addClass('first'); // this selects the first li of the .list
$('.list li').eq(1).addClass('second'); // this selects the second li in the .list (count starts at 0)
$('.list li').eq(1).next().addClass('next'); // this selects the next li in the .list
$('.list li').eq(1).prev().addClass('prev'); // this selects the previous li in the .list
$('.list').parent().addClass('parent'); // this selects parent of the .list then stops
$('.list').parents().addClass('parents'); // this selects parents of the .list in this case container two and the body
$('.list').closest('.container').addClass('closest'); // this selects the closest parent of the .list then stops
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment