The beauty of jquery method is that they return jquery object which can be used further to call another method. This is called COMMAND CHAINING where you can use multiple methods on a single set of elements. This is very helpful in many ways. See the example below.
Without Chaining
<script type="text/javascript">
$(document.)ready(function(){
$(“#div1").removeClass(“red");
$(“#div1").addClass(“blue");
$(“#div1").css(“border","1px solid #000")
});
</script>
This script is traversing through the entire DOM and removing class from div ID div1. Then again it’s traversing through the DOM and adding a class blue and traversing through again to add a border. Now, this traversing could have been avoided using jquery chaining. It’s surely going to perform better, saving you from writing unnecessary code and keeping the code cleaner.
With Chaining
<script type="text/javascript">
$(document.)ready(function(){
$(“#div1").removeClass(“red")
.addClass(“blue")
.css(“border","1px solid #000")
});
</script>
No comments:
Post a Comment