Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created March 25, 2014 11:02
Passing A Function To jQuery's Attr() Method For Implicit Iteration
$( "..." ).attr( "rel", "myRel" );
$( "..." ).each(
function( index ){
$( this ).attr( "rel", ("MyRel" + index" ) );
}
);
<!DOCTYPE HTML>
<html>
<head>
<title>jQuery Attr() Method And Function Argument</title>
<style type="text/css">
#p1 {
background-color: #FFEEEE ;
}
#p2 {
background-color: #EEFFEE ;
}
#p3 {
background-color: #EEEEFF ;
}
</style>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript">
// When the DOM is ready, intialize it.
$(function(){
// Set the ID of each P tag.
$( "p" ).attr(
"id",
function( index ){
// Return the value that we want to store into
// the ID attribute.
return( "p" + (index + 1) );
}
);
});
</script>
</head>
<body>
<h1>
jQuery Attr() Method And Function Argument
</h1>
<p>
Paragraph One
</p>
<p>
Paragraph Two
</p>
<p>
Paragraph Three
</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment