Home/Jquery/attr() Method

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.

READ  serialize() method in Jquery

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>

Leave A Comment