Category Archives: Jquery

removeAttr() Method

.removeAttr()

Remove an attribute from each element in the set of matched elements.

HTML :

<table border=”1″>
<tr><td>This is first table</td></tr>
</table>

JQUERY:

$(document).ready(function() {

$(“table”).removeAttr(“border”);

});

OUTPUT DOM :

<table>
<tr><td>This is first table</td></tr>
</table>

NOTE :

From above JQ, removeAttr() remove th border attribute in the selected table

attr() Method

attr() :

The attr() method sets or returns attribute values of selected elements.

Getting attribute

JQUERY : 1

alert($(“#img1”).attr(“href”));

From above JQ, the message box will show the link of img1(which element having id as img1). Here its getting
value of attribute

Set attribute

JQUERY : 2

$(“#img1”).attr(“href”, “http://www.google.in”);

From above JQ, the link will apply to the href in to the element which having id as img1.

Example 1:

HTML :

<body><img /> <img /></body>

JQUERY :

$(“img”).attr({
src: “/image/test.gif”,
title: “jQuery attr() method”,
alt: “Not Available”
});

OUTPUT DOM :

<body>
<img src=”/image/test.gif” title=”jQuery attr() method” alt=”Not Available” />
<img src=”/image/test.gif” title=”jQuery attr() method” alt=”Not Available”/>
</body>

clone() Method

clone()

  •   Create a deep copy of the set of matched elements.
  •   We can use clone copy in to two ways,clone()/clone(true).It also support a boolean parameter to indicate whether need to copy the event handlers and data along with the matched elements.First we see the clone()

METHOD 1 :  clone()

Use clone() to create a copy of the above elements, and place the copied elements after the div tag that contains a class name of  “mainDiv”.

HTML :

<div>
<p>Testing for clone() method in jquery
</div>

JQUERY :

$(‘.mainDiv’).clone().insertAfter(“.mainDiv”);

OUTPUT DOM :

<div>
<p>Testing for clone() method in jquery</p>
</div>

<div>
<p>Testing for clone() method in jquery
</div>

NOTE:
After executing JQ, the element which has class name as mainDiv will be copied and placed after the element which has class name of mainDiv

METHOD 2: clone(boolean)
It also support a boolean parameter to indicate whether need to copy the event handlers and data along with the matched elements.

HTML :

<button id=”cloneBtn”>clone()</button>

JQUERY :

$(“#cloneBtn”).click(function () {

$(‘.mainDiv’).clone().insertAfter(“.mainDiv”);

});

STEP 1 : $(‘#cloneBtn’).clone().insertAfter(“#cloneBtn”);

Above will copy only element without any event handler.

STEP 2 ; $(‘#cloneBtn’).clone(true).insertAfter(“#cloneBtn”);

Above will copy event handler along with matched elements, you should use clone(true).

Note : For better understanding

 If we create button dynamically with the clone method,it will copy element and eventhandler(thats is action to be performed ) when we use
clone(true).

click() vs bind() vs live() vs delegate()

click() vs bind()

Bind an event handler to the “click” JavaScript event, or trigger that event on an element.First, .click(function) is literally a shortcut for .bind(‘click’, function), they are equivalent.
Use them when binding a handler directly to an element.

Example 1:

$( “#div1” ).bind( “click”, function( e ) {

alert(“Click event using bind()”);

});

$( “#members li a” ).click( function( e ) {

alert(“Click event using click()”);

} );

Cons :

  •     The method attaches the same event handler to every matched element in the selection.
  •     It doesn’t work for elements added dynamically that matches the same selector.
  •     There are performance concerns when dealing with a large selection.

Main difference between bind() vs delegate()
Example 2:

$(document).ready(function(){
$(“table”).delegate(“td”,”click”,function(){
alert(‘I am’ + $(this).text());
});
});

If we append new td dynamically in to the above table the click event will be apply for it(ie., it will apply for future
element also), but bind will not bind the event to the future element

bind() vs live()

The advantage of live and delegate function that they attaches event to those elements also which are added/appended after DOM is loaded.

 Example 3:

$(‘a’).live(‘click’, function() { alert(“Thats New!”) });

jQuery binds the alert function to the $(document) element, along with ‘click’ and ‘a’ as parameters. Any time an event bubbles up to the
document node, it checks to see if the event was a click and if the target element of that event matches the ‘a’ CSS selector. If both are true,
the function executes.

Difference :

  • live function can’t be used in chaining. live function needs to be used directly on a selector/element.

    for example : Wrong Code

$(‘#foo’).children(‘table’).find(‘td’).live(‘click’, function(){
});

  for example : Correct code

$(‘#foo’).children(‘table’).find(‘td’).delegate(‘click’, function(){
});

  • There is one more difference in terms of performance, if the context is not specified with the live function. Context means you are setting the search limit within a specific node.If you don’t specify the context with live function then it attaches the handler to the document by default and when executed it traverse through the DOM which causes a performance issue.

$(document).ready(function(){
$(“#tble1 td”).live(“click”,function(){
alert(“test”);
});

});

In the above code, no context is specified so event gets attached to the document by default. It causes a huge performance issue. But with jQuery 1.4, you can specify the context with live function also.

$(document).ready(function(){
$(“td”,$(“#tble1”)

[0]).live(“click”,function(){
alert(“test”);
});
});

click() and dblclick()

click() : Fire when mouse single click on the matched element.

dblclick() : Fire when mouse double clicks on the matched element.

Example :

$(‘#singleClick’).click(function(){

$(‘#singleClick’).css(“border”, “1px solid red”);

});

$(‘#doubleClick’).dblclick(function(){

$(‘#doubleClick’)..css(“border”, “1px solid blue”);
});

Note :

Step 1: Element has id as “singleclick”  will apply border as red ( single click ).
Step 2: Element has id as  “doubleClick”  will apply border as blue in ( double click ).

.empty() vs .remove() vs .detach()

jQuery provides various methods to remove elements from DOM. These methods are

  • .empty()
  • .remove() and
  • .detach()

.empty(): This method removes all the child element of the matched element from DOM.

.remove(): This method used when you want to remove the element itself, as well as everything inside it.
(This method takes elements out of the  DOM)

.detach(): This method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements.
detach method is useful in the scenario of removing elements are to be reinserted/added into the DOM at a later time.

Example 1:

HTML :
<div>
<div>HELLO</div>
<div>BYE</div>
</div>

JQUERY :

$(‘.hello’).empty();
$(‘.hello’).remove();

OUTPUT DOM : empty()

<div>
<div></div>
<div>BYE</div>
</div>

OUTPUT DOM : remove()

<div>
<div>BYE</div>
</div>

Exampke 2:

var temp = null;
temp = $(“#dvjQ”).detach();
$(“#dvjQ”).html(temp);

Note : Then detach the div and attach it again  remove also do the same the difference is it also erase the event associated with the element.(hover event….)

.add() Method

.add()

Add elements to the set of matched elements.

HTML:

<p>Hello</p><span>Hello Again</span>

JQUERY:

$(“div”).css(“border”, “2px solid red”)
.add(“p”)
.css(“background”, “yellow”);

This JQ will,

Step : 1  find the div and apply the red to the border
Step : 2  Then add p element to the end of the div and apply background as yellow

OUTPUT :

.find() vs .filter()

Both filter() and find() methods are very similar, except the former is applies to all the elements, while latter searches child elements only.

find() searches the descendants of the elements in the matched set. filter() searches only the elements in the matched set.

To simple

 1.filter() – search through all the elements.
 2.find() – search through all the child elements only.

filter() :

$(‘div’).filter(‘#div1’).css(‘background’,’red’);

find() :

$(‘div’).find(‘#div1’).css(‘background’,’red’);

Difference Between jQuery Text() And HTML()

 

In this post you will learn about the difference between jQuery text and HTML.

.html() – This jQuery function gets/sets the HTML of any element.
.text()- This jQuery function gets/sets the text (innertext) of any element.

Let’s take an example. I have placed a div element, which have a span tag as child and some text.

HTML :

This code given below is the sample HTML document

<div id=”dvFirst”>
<span>jQuery By Example </span>
</div>

Now in .ready() event, both the functions .html() and .text() functions are used on div and the output is placed in alert box.

JQUERY :

$(function () {
alert(“Div HTML is: ” + $(“#dvFirst”).html());
alert(“Div content is: ” + $(“#dvFirst”).text());
});

Now, when you view this page in browser, there will be 2 alerts.

First alert box, will display below text.

Div HTML is: <span>jQuery By Example </span>

And second alert box, will display below text.

Div content is: jQuery By Example

As you see, that the .html() function provides you the inner html and text of the element while text function gives you only text.