Get a free trial // Grow your CSS skills // Land your dream job

Working with Attributes

Last updated on:

Setting Single Attribute

$("img").attr("src", "/images/banner.jpg");

Setting Single Attribute (with function)

$("div").attr("id", function (arr) {
    return "div-id" + arr;

Setting Multiple Attributes

       src: "/images/banner.jpg",
       title: "banner",
       alt: "banner"

Getting Attribute

var $source = $("img").attr("src");

Reference URL


  1. LuK
    Permalink to comment#

    Just getting into vars with jQuery and because of this I have a question to the last example…is it just your favourite way of naming a variable $source or do I have to do this like this to make it work?

    • TerranRich
      Permalink to comment#

      It just appears to be a good way of writing variables that have to do with jQuery return values. I like to use it when setting a jQuery object to a variable — for example, var $elems = $(‘#mydivs’);

  2. nhamngahanh
    Permalink to comment#

    This is what I need .

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

There's a whole bunch of content on CSS-Tricks.

Search for Stuff   •   Browse the Archives

Get the Newsletter ... or get the RSS feed