The first few topics will cover basic things which are actually left redundant by the awesomeness of jquery, but i guess it will be a good starting point.
So lets get started with Part 1 : DOM selection. (I am assuming the reader is familiar with the acronym DOM.)
$("selecter") in jquery makes selecting elements from the document
real easy right ? But how to do it using plain js ? There are
different ways depending upon the element.
Selecting by id
//select the first div by its id $("#myid") //jquery document.getElementById("myid"); //plain js // note that plain js selector properties and methods cannot be // applied in the first case as the plain js way returns an object // while jquery returns an array of js objects. in this case the // length will be 1 as we are getting it by id. To use it any way $("#myid").style;
Accessing by Tag Name
Notice the getElements This will return an array of size equal to number of ul elements in the document
Accessing Children of elements
In js all elements are referred to as nodes of the DOM tree.
<div id="childtest">Hello world. Now check this <a href="">link</a></div>
var arr = document.getElementById("childtest").childNodes;
The output if logged in firebug console will show an array of all
children of the element childtest selected. But it will be different
$("#childtest").children() will return.
TextNode and accessing the text
If you have already logged the above example to a firebug console, you
can see that apart from the actual child element ie anchor tag, it
also shows a Textnode (which is skipped by the jquery
$("#childtest").children() code). To get its value just select
that particular child and get the property 'nodeValue'. This is how
.text method does the job.
Accessing the siblings
document.getElementById("childtest").childNodes.nextSibling; // or ...childNodes.previousSibling
So how to get all siblings of an element? Well, to do this, first we can traverse to an elements parent and then get all its childNodes.
Accessing the parent element
As simple as it can get
So, this was pretty much about selecting the elements. In the next part we will see how to manipulate them by dealing with css and also how to make fancy things.