How to work with attr() Jquery -


i working attr()

from last few months , i'm new jquery. taking references jqueryapi website , saw :

<div>zero-th <span></span></div> <div>first <span></span></div> <div>second <span></span></div>  $("div")     .attr( "id", function( arr ) {         return "div-id" + arr;      })     .each(function() {         $( "span", ).html( "(id = '<b>" + this.id + "</b>')" );      }); 

i don't thing can explain it? this variable , how these id's incrementing?

the output

enter image description here

the function pass attr function second parameter receives index position of element matching. arr argument of function index of element. first 0, second 1 , on.

it index used assemble new id attribute elements.

reference: http://api.jquery.com/attr/#attr-attributename-function

.attr( attributename, function )

attributename name of attribute set.

function type: function( integer index, string attr )
function returning value set. current element. receives index position of element in set , old attribute value arguments.

in each command, callback receives item being iterated over. item represented this variable. specify different variable use other this naming argument in callback:

.each(function(the_element) {   $( "span", the_element ).html( "(id = '<b>" + the_element.id + "</b>')" ); }); 

by naming first augment in callback the_element can use variable represent current element - same using this variable being more specific regard name want use.


Comments