I was wondering how jQuery traverses the DOM when you use a selector. Does it look up each "first level" element, and then look inside each one of them? Or does it look at every children of those "first level" elements one by one?
Let me explain what i imagined with some quick examples, given the following selector :
$("div p#target")
Does it proceed more like :
[1] <div>
[3] <div>
[5] <p id="target"></p>
</div>
</div>
[2] <div>
[4] <div>
<p></p>
</div>
</div>
Or like :
[1] <div>
[2] <div>
[3] <p id="target"></p>
</div>
</div>
<div>
<div>
<p></p>
</div>
</div>
jQuery provides methods such as attr(), html(), text() and val() which act as getters and setters to manipulate the content from HTML documents. Document Object Model (DOM) - is a W3C (World Wide Web Consortium) standard that allows us to create, change, or remove elements from the HTML or XML documents.
Three useful jQuery methods for traversing up the DOM tree are: parent() parents() parentsUntil()
We can also traverse up the DOM tree, using the parentNode property. while (node = node. parentNode) DoSomething(node); This will traverse the DOM tree until it reaches the root element, when the parentNode property becomes null.
Having the access to a certain node in the DOM, there are ways to traverse through the DOM using its related nodes. We can move up or down the DOM tree, or we can move sideways staying at the same DOM level.
Traversal happens in the same order the elements are in the DOM:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>query traversal order</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
</head>
<body>
<ul>
<li id="parent1">
<ul>
<li id="child1"></li>
<li id="child2"></li>
</ul>
</li>
<li id="parent2">
<ul>
<li id="child3"></li>
<li id="child4"></li>
</ul>
</li>
</ul>
<script type="text/javascript">
// keep a list of ids
var arr = [];
// loop over all li elements
$('li').each(function(){
// add their id to the array
arr.push($(this).attr('id'));
});
// show contents of the array
alert(arr.join(', '));
</script>
</body>
</html>
This will alert "parent1, child1, child2, parent2, child3, child4";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With