Introduction to JQUERY - Traversing with the add() method

Guest Posts Paolo Nikko Nuñal

Traversing HTML elements is as easy as pie, it may sound cliche but JQUERY makes it easy for you to traverse elements with a wide variety of methods that you can use. One of which is the add() method. So you might be wondering how does the add() method works, it's easy, from the word itself, it adds elements to a set of matched elements.

Syntax:

$(selector).add([ELEMENT],[CONTEXT])

ELEMENT- (REQUIRED) This one specifies the selector expression that will include a JQUERY object that contains one or more elements or otherwise an HTML snippet to be added to an existing group of elements.

CONTEXT - (OPTIONAL) Determines the point of the document in which the selector or expression should start matching.

Code


<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
     $("h1").add("p").css("background-color","yellow");
});
</script>
</head>
</body>
<div id="section">
<h1>Welcome</h1>
<h1>to the</h1>
<h1>Jungle</h1>
</div>
</body>
</html>


In our example above, it will search all <h1> and adds all paragraphs to the JQUERY object with a color of yellow. Here's another example.

html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
     $("div").add("p").css("border","2px solid green");
});
</script>
<style>
      div { width: 50px; height: 20px;}
</style>
</head>
</body>
<div id="section">
<div></div>
<br>
<div></div>
<br>
<div></div>
</body>
</html>


In the last example it traverses all <div>'s and makes a green border. The add() method is useful if you are traversing large files that has the same class or HTML element to quickly modify them according to your liking.