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

Was it helpful?

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");
});

http://jsfiddle.net/eC2cQ/

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:

  • if you want custom attributes on elements in new pages, you are better off changing your back-end process to create these new attributes. To expand on this: if you are hand-coding new pages, simply write out the new attributes; if you are using a server-side technology, use the templating system you're already using to write out these new attributes.
  • your example is not good practice: title attributes are useful to many people and machines. Replacing them with data-title prevents a lot of standard tech from finding the information contained in them. There is extra meaning implied by data-attributes, that they are extra, application-specific information, and link titles are better used in the generic way.
  • it's redundant: if you can read a data-attribute, you can also read a normal attribute.
  • there will be other ways to do this without using jQuery, but it's a pretty typical library in use these days
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top