In jQuery, let’s say we have 2 ways to navigate through the DOM elements;
- Through the use of CSS colon selectors (e.g.
var x = $("#someElement:after")) - Through the jQuery functions (e.g.
var x = $("#someElement").prev())
Now my questions are:
- Is the return type same in both the cases?
- What is the difference in navigating through the DOM in both the
approaches? - Can we apply the same jQuery function to the result of both these
statements? E.g.x.css("someProp","someVal")
I’m not sure that “:after” exists but other than that:
1) The return type will be exactly the same for either (So long as its a valid selector)
2) The difference is fairly slight, its mostly about how you prefer do to things and in certain cases the “:first” may not be exactly what you want, in a loop for example. There are arguments about which has the best overhead but I don’t know enough to comment.
3) Absolutely, as the return type is exactly the same (A jQuery element) you can use them in exactly the same way.
E.G:
$(“#Test”).parent();
would return exactly the same as
$(“#Test:parent”);
Example:
http://jsfiddle.net/HenryGarle/2qcpK/
This would result in the DOM looking like: