Reputation: 4651
I want to replace a tag with span tag using javascript or jquery in the below mentioned code.
<a class="multi-choice-btn" id="abcd123">
<img class="x-panel-inline-icon feedback-icon " src="../images/choice_correct.png" id="pqrs123">
</a>
This should be changed as below.
<span class="multi-choice-btn" id="abcd123">
<img class="x-panel-inline-icon feedback-icon " src="../images/choice_correct.png" id="pqrs123">
</span>
Replacement has to be done on basis of class "multi-choice-btn" as id will be dynamic.
Please help.
Upvotes: 0
Views: 5068
Reputation: 79830
Try using replaceWith and a small attrCopy logic. See below,
DEMO: http://jsfiddle.net/4HWPC/
$('.multi-choice-btn').replaceWith(function() {
var attrCopy = {};
for (var i = 0, attrs = this.attributes, l = attrs.length; i < l; i++) {
attrCopy[attrs.item(i).nodeName] = attrs.item(i).nodeValue;
}
return $('<span>').attr(attrCopy).html($(this).html());
});
Upvotes: 1
Reputation: 14827
You can do as following:
$('a').contents().unwrap().wrap('<span></span>');
DEMO: http://jsfiddle.net/XzYdu/
If you want to keep the attribute you can do as following:
// New type of the tag
var replacementTag = 'span';
// Replace all a tags with the type of replacementTag
$('a').each(function() {
var outer = this.outerHTML;
// Replace opening tag
var regex = new RegExp('<' + this.tagName, 'i');
var newTag = outer.replace(regex, '<' + replacementTag);
// Replace closing tag
regex = new RegExp('</' + this.tagName, 'i');
newTag = newTag.replace(regex, '</' + replacementTag);
$(this).replaceWith(newTag);
});
DEMO: http://jsfiddle.net/XzYdu/1/
Upvotes: 2
Reputation: 193261
Not the shortest but working:
$('.multi-choice-btn').replaceWith(function() {
return $('<span>', {
id: this.id,
`class`: this.className,
html: $(this).html()
})
});
See http://jsfiddle.net/dfsq/unVfp/
Upvotes: 2
Reputation: 35409
var anchor = document.getElementById("abcd123"),
span = document.createElement("span");
span.innerHTML = anchor.innerHTML;
span.className = anchor.className;
span.id = anchor.id;
anchor.parentNode.replaceChild(span,anchor);
Upvotes: 2