Basic jQuery Tutorial: Add Remove Attribute

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,

10 Comments Basic jQuery Tutorial: Add Remove Attribute

  1. Vadim

    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.

    Reply
  2. Pingback: WordPress Rocker

  3. Pingback: Design Gala

  4. Pingback: SiteSyrup

  5. Pingback: organic web

  6. Pingback: organic web

  7. max hodges

    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

    Reply
  8. v_omar

    Hello

    There is a way not to repeat several times removeAttr

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

    It can be used so
    $(“#myLink”).removeAttr(“style”,”title”);

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>