Skip to content

Instantly share code, notes, and snippets.

@sahinsf
Created June 14, 2012 20:33
Show Gist options
  • Save sahinsf/2932775 to your computer and use it in GitHub Desktop.
Save sahinsf/2932775 to your computer and use it in GitHub Desktop.
jQuery Practice | Traversing | Events | Selectors | Manipulation | Ajax | Effects
http://api.jquery.com/category/selectors/
http://api.jquery.com/category/traversing/
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>HTML Document</title>
<style type="text/css">
ul li{color: red;}
.emphasis{color: green;}
ul.emphasis > li {}
</style>
</head>
<body>
<div class="container">
<ul class="emphasis">
<li>Hello 1</li>
<li>Hello 2 <br> Hello</li>
<li>
<ul>
<li>Hello 3</li>
<li>Hello 4</li>
<li><a href="#">Hello 5</a></li>
</ul>
</li>
</ul>
<p>a paragraph</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js" type="text/javascript"></script>
<script >
$(function(){
var sel; //select something
//sel= $('li')[0]; //not a jQuery object
//sel = $('li').eq(0); //jQuery object
sel = $('li').find('ul').children('li:nth-child(1)').next(); //Hello 4
//sel = $('li').eq(4); // Hello 4
console.log(sel);
//////////////////====TRAVERSING==========/////
//.add() Add elements to the set of matched elements.
var jqAdd = $('li').add('p'); //.add() doesn't add elements to the dom //.add() actually just adds elements to the array of selected dom items.
console.log(jqAdd.length); // 6 li + 1 p = 7 elements
//.andSelf() Add the previous set of elements on the stack to the current set.
$('li').eq(1) //initial stack = li 2
.nextAll() // Second Stack: li > ul > li 3, li 4, li5
.andSelf();// initial tack added to the current stack: li > ul > li 3, li 4, li5 + li 2
//.children() only direct children not all descendant (NOT grand children like .find() )
$('ul.emphasis').children('li').css('color','green'); // only single level down li elements
//.contents() ==> children + text + nodes
$('ul.emphasis').contents().filter(function(){ //CANNOT do contents('li')
return this.nodeType==3;
})
.wrap("<p></p>");
//.closest() Get the first element that matches the selector, BEGINNING AT THE CURRENT ELEMENT (unlike parents()) and progressing up through the DOM tree.
$('a').closest('a').css('color', 'yellow'); //REQUIRES a selector to match with
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment