Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change HTML attribute names with jQuery?

Tags:

html

jquery

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?


1 Answers

There is no built-in method/function to "rename" an attribute in javascript, 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');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="testingCase" href="#" title="name of testing case">Blabla</a>
<a class="testingCase" href="#" title="name of another testing case">Bloo</a>

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

like image 50
nickf Avatar answered Sep 12 '25 12:09

nickf