Using jQuery, how would you replace every <acronym>
tag with <abbr>
?
Asked
Active
Viewed 651 times
2

Gert Grenander
- 16,866
- 6
- 40
- 43

Phillip Senn
- 46,771
- 90
- 257
- 373
-
1Not sure why you would want to do this in jQuery, or JavaScript full stop. The correct markup should be written into the HTML document — or even better, keep a glossary of terms in XML or JSON (on server side) and transform instances of the term text nodes in the HTML by wrapping them with abbreviation tags. – DigiKev Jul 06 '12 at 22:55
6 Answers
3
$('acronym').each(function() {
var $this = $(this);
$this.before('<abbr>' + $this.html() + '</abbr>');
$this.remove();
});

sje397
- 41,293
- 8
- 87
- 103
-
2You'll want to copy any attributes over too: http://stackoverflow.com/questions/2048720/get-all-attributes-from-a-html-element-with-javascript-jquery – David Tang Dec 21 '10 at 02:51
2
I'd try this, but I offer no warranty.
$('acronym').each(function(index)
{
var old = this;
var newElement = $("<abbr></abbr>");
$.each(this.attributes, function(index)
{
$(newElement).attr(old.attributes[index].name, old.attributes[index].value);
});
$(newElement).html(old.html());
$(this).after(newElement).remove();
});
Good luck, and tell me if it's brokeded. If it's brokeded, I'll try to fix it.

Blender
- 289,723
- 53
- 439
- 496
1
Use jQuery's replaceWith. I am assuming you are only using the title attribute.
$("acronym").each(function(){//for each acronym element
var abbr = $("<abbr></abbr>");//create a new abbr element
var title = $(this).attr("title");//get the title attribute from the acronym element
abbr.attr("title",title);//add it to the new abbr element
abbr.html($(this).html());//add in the content of the acronym element
$(this).replaceWith(abbr);//replace the old with the new!
});

Adam
- 43,763
- 16
- 104
- 144
1
Something along the lines of:
$('acronym').each(function(i, el) {
$(this).replaceWith($('<abbr></abbr>').html($(this).html()));
});
Edit: You'll want to copy attributes too if you have any... Took for granted that you don't.
- Christian

Christian Joudrey
- 3,441
- 25
- 25
1
$('acronym').each(function() {
$(this).replaceWith('<abbr>' + $(this).html() + '</abbr>');
});

Kai
- 2,967
- 1
- 22
- 28
1
$("acronym").each(function(idx,HTML) {
$(this).replaceWith('<abbr title="'+this.title+'">'+HTML+'</abbr>');
});

Gert Grenander
- 16,866
- 6
- 40
- 43