Basic jQuery Tutorial: Add Remove Attribute

March 4, 2010 |  by Mukesh Chapagain

In this article, I will be showing you how to add or remove HTML attributes. HTML attributes like title, href, src, etc. For example:-

<img src="abc.jpg" class="test" alt="abc" />

Here: src, class, alt, title are attributes.

You can add attributes like above through jQuery. You can also remove the attributes with jQuery.

VIEW DEMO

Here is the HTML source. This contains a link with id ‘myLink’ and Add and Remove buttons with id ‘add’ and ‘remove’ respectively.

<div class="content">
<a id="myLink" href="#">This is my LINK</a>
</div>
 
<button>Add</button>
<button>Remove</button>

Adding Attribute

The following function works as follows:
- myLink is the id of a href link
- add is the id of add button
- when add button is clicked, some style (css) is added to the link with id ‘myLink’
- after that, ‘title’ attribute is added to link with id ‘myLink’

$("#add").click(function(){
	$("#myLink").css({"font-weight":"bold", "color":"red", "text-decoration":"line-through"});
	$("#myLink").attr("title","My Link Title");
});

Removing Attribute

The following function works as follows:
- there is a button with id ‘remove’
- when remove button is clicked, the following things happen:
- ‘style’ attribute is removed from the link with id ‘myLink’
- ‘title’ attribute is removed from the link with id ‘myLink’

$("#remove").click(function(){
	$("#myLink").removeAttr("style");
	$("#myLink").removeAttr("title");
});

VIEW DEMO

Cheers,

Related Posts with Thumbnails

2 Comments


  1. This is cool that you are writing this jQuery tutorials for beginners, but could you write some on jQuery syntax, because sometimes a beginner can get confused on parenthesis and curly brackets sets, when they gets more than two pairs.

  2. Hi, I’m trying to remove all the TITLE attributes from the img elements on my site. WordPress is adding them, and I tried to change the WP code, but too many things depend on the title tags being in there, so I’d like to see if I can remove them with jQuery.

    I tried adding this to my head

    $(‘img’).removeAttr(“title”);

    but it’s not working.
    Any ideas? I’m very new to jQuery.

    Cheers!
    Max

Trackbacks

  1. WordPress Rocker
  2. Design Gala
  3. SiteSyrup
  4. organic web
  5. organic web

Leave a Reply