tags:

views:

3011

answers:

2

I would like to change all the names of the attributes where class="testingCase" throughout all my whole html document.

e.g. Change:

<a class="testingCase" href="#" title="name of testing case">Blabla</a>
<a class="testingCase" href="#" title="name of another testing case">Bloo</a>

To this:

<a class="testingCase" href="#" newTitleName="name of testing case">Blabla</a>
<a class="testingCase" href="#" newTitleName="name of another testing case">Bloo</a>

I was thinking of a find and replace but that seems a lot of code for something so easy. Is there a jQuery function for this or a simple method?

Thank you,

Ice

+5  A: 

I don't think you can "rename" an attribute, but you can create new attributes and remove other ones...

$('a.testingCase[title]').each(function() {
    var $t = $(this);
    $t
        .attr({
            newTitleName : $t.attr('title'),
        })
        .removeAttr('title')
    ;
});

Edit: added in the bit that makes it only select a elements with class="testingCase"

nickf
so you know, looks like this is using jquery ..
benlumley
well, yeah - wasn't that the question?
nickf
+3  A: 

I don't think you can change an attribute name but what you can do is :

  • get all the <a> tags with a title attribute;
  • foreach of them, create a newTitleName attribute with the same value as the title;
  • then delete the title attribute.

JQuery let you do that with builtin functions this way :

/* get all <a> with a "title" attribute that are testingCase
then apply an anonymous function on each of them */

$('a.testingCase[title]').each(function() {   

    /* create a jquery object from the <a> DOM object */
    var $a_with_title = $(this);    

    /* add the new attribute with the title value */
    $a_with_title.attr("newTitleName", $a_with_title.getAttribute('title'));

    /* remove the old attribute */
    $a_with_title.removeAttr('title'); 

});
e-satis