Replace an element name while retaining the attributes with jquery
I'm trying to create a jquery setup where all instances of <i>
are changed 开发者_StackOverflowto <em>
. It's easy enough to do with:
$("i").each(function(){
$(this).replaceWith($('<em>' + this.innerHTML + '</em>'));
});
But what I am having trouble figuring out is how to change all the <i>
tags but retain each ones individual attributes. So if I have <i style="background-color: #333;" alt="Example" title="Example">Example Text</i>
I would like it to change to <em style="background-color: #333;" alt="Example" title="Example">Example Text</em>
Thanks for any help!
Wrong approach IMO.
I'd recommend replacing the actual elements themselves directly in the DOM. Maybe this question helps:
jQuery convert DOM element to different type
It is simple
$(this).attributes(); will get you all the attributes of the i tag for every instance simply place it into your replace function.
I am not sure how can you play with a function but in my knowledge code will be something like this.
$("i").each(function(){ var attribute = $(this).attributes(); $(this).replaceWith($('<em'+attributes+'>'
+ this.innerHTML + '')); });
Hope it helps.
精彩评论