Could be done like that too:
$('a').attr('data-title', function () {
return this.title
}).removeAttr('title');
Question
is there any way we can change an element itself with jQuery or basic Javascript. for example : we have an Html Tag as <a href="mysite.com" title='titlevalue'>Link</a>
, can we replace it like this <a href="mysite.com" data-title='titlevalue'>Link</a>
.
Yeah, we can do add/remove title/data-title attribute however we have quite a lot of links so it would be better if we can have such sort of things. Searched on Google and here but didn't find anything like this, just changing the values of an attribute and add/remove of attributes.
Please Advice.
Thanks
Solution 4
Could be done like that too:
$('a').attr('data-title', function () {
return this.title
}).removeAttr('title');
OTHER TIPS
If you want to add the data title attribute to each anchor tag, by using the value in the title attribute, you can do something like this:
$("a").each(function(){
$(this).attr("data-title", $(this).attr("title"));
$(this).removeAttr("title");
});
That will change title to data-title in all a-Tags:
$("a").each(function() {
$(this).attr("data-title", $(this).attr("title"));
$(this).data("title", $(this).attr("title"));
$(this).removeAttr("title");
});
Hmm... without jQuery... (just because it's always nice to have that option)
var el = document.getElementsByTagName("a");
for(i=0; i < el.length; i++) {
el[i].setAttribute("data-title", el[i].getAttribute("title"));
el[i].removeAttribute("title");
}
Using jQuery, you could do the following:
// find each a tag with a title attribute
$( 'a[title]' ).each( function ( index, item ) {
// cache your jQuery object
var $item = $(item);
// replace and remove the attributes
$item.attr( 'data-title', $item.attr( 'title' ) );
$item.removeAttr( 'title' );
});
Some points of note: