更改标记但保留属性和内容 - jQuery / Javascript [英] Change the tag but keep the attributes and content -- jQuery/Javascript

查看:135
本文介绍了更改标记但保留属性和内容 - jQuery / Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文字

更改为

<p href="page.html" class="class1 class2" id="thisid">Text</p>

我熟悉jQuery的 replaceWith 但是据我所知,这不保留属性/内容。

I'm familiar with jQuery's replaceWith but that doesn't keep attributes/content as far as I know.

注意:为什么p会有 href ?因为我需要在另一个事件上将 p 更改回 a

Note: Why would p have a href? Cuz I need to change p back to a on another event.

推荐答案

试试这个:

var $a = $('a#thisid');
var ahref = $a.attr('href');
var aclass = $a.attr('class');
var aid = $a.attr('id');
var atext = $a.text();
$a.replaceWith('<p href="'+ ahref +'" class="'+ aclass +'" id="'+ aid+'">'+ atext +'</p>');

这篇关于更改标记但保留属性和内容 - jQuery / Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆