简体   繁体   English

用span标签替换标签

[英]Replace a tag with span tag

I want to replace a tag with span tag using javascript or jquery in the below mentioned code. 我想在下面提到的代码中使用javascript或jquery将标签替换为span标签。

<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. 替换必须基于类“ multi-choice-btn”完成,因为id将是动态的。

Please help. 请帮忙。

You can do as following: 您可以执行以下操作:

$('a').contents().unwrap().wrap('<span></span>');​

DEMO: http://jsfiddle.net/XzYdu/ 演示: 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/ 演示: http : //jsfiddle.net/XzYdu/1/

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/ 参见http://jsfiddle.net/dfsq/unVfp/

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);​

http://jsfiddle.net/tCyVH/ http://jsfiddle.net/tCyVH/

Please see this attached jsFiddle . 请参阅此附件jsFiddle

var props = $(".multi-choice-btn").prop("attributes");

var span = $("<span>");

$.each(props, function() {
    span.attr(this.name, this.value);
});

$(".multi-choice-btn").children().unwrap().wrapAll(span);​

Try using replaceWith and a small attrCopy logic. 尝试使用replaceWith和小的attrCopy逻辑。 See below, 见下文,

DEMO: http://jsfiddle.net/4HWPC/ 演示: 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());

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM