jQuery: how to change tag name?

前端 未结 17 947
無奈伤痛
無奈伤痛 2020-11-28 07:37

jQuery: how to change tag name?

For example:


    $1

I need

$1
<
17条回答
  •  我在风中等你
    2020-11-28 08:21

    Take him by the word

    Taken the Question by Word "how to change tag name?" I would suggest this solution:
    If it makes sense or not has to be decided case by case.

    My example will "rename" all a-Tags with hyperlinks for SMS with span tags. Maintaining all attributes and content:

    $('a[href^="sms:"]').each(function(){
      var $t=$(this);
      var $new=$($t.wrap('
    ') .parent() .html() .replace(/^\s*<\s*a/g,'\s*$/g,'span>') ).attr('href', null); $t.unwrap().replaceWith($new); });

    As it does not make any sense to have a span tag with an href attribute I remove that too. Doing it this way is bulletproof and compatible with all browsers that are supported by jquery. There are other ways people try to copy all the Attributes to the new Element, but those are not compatible with all browsers.

    Although I think it is quite expensive to do it this way.

提交回复
热议问题