使用jQuery来改变一个HTML标签?

这可能吗?

例:

$('a.change').click(function(){ //code to change p tag to h5 tag }); <p>Hello!</p> <a id="change">change</a> 

因此,点击更改锚点应该使<p>Hello!</p>部分变成(作为示例)一个h5标签,以便在点击之后最终得到<h5>Hello!</h5> 。 我意识到你可以删除p标签,并用h5replace它,但实际上修改HTML标签有吗?

一旦创build了一个dom元素,我相信标签是不可改变的。 你必须做这样的事情:

 $(this).replaceWith($('<h5>' + this.innerHTML + '</h5>')); 

这里有一个扩展,将尽可能多的元素,尽可能多的元素…

用法示例:

保留现有的类和属性:

$('div#change').replaceTag('<span>', true);

要么

放弃现有的类和属性:

$('div#change').replaceTag('<span class=newclass>', false);

甚至

用跨度replace所有div,复制类和属性,添加额外的类名

$('div').replaceTag($('<span>').addClass('wasDiv'), true);

插件来源:

 $.extend({ replaceTag: function (currentElem, newTagObj, keepProps) { var $currentElem = $(currentElem); var i, $newTag = $(newTagObj).clone(); if (keepProps) {//{{{ newTag = $newTag[0]; newTag.className = currentElem.className; $.extend(newTag.classList, currentElem.classList); $.extend(newTag.attributes, currentElem.attributes); }//}}} $currentElem.wrapAll($newTag); $currentElem.contents().unwrap(); // return node; (Error spotted by Frank van Luijn) return this; // Suggested by ColeLawrence } }); $.fn.extend({ replaceTag: function (newTagObj, keepProps) { // "return" suggested by ColeLawrence return this.each(function() { jQuery.replaceTag(this, newTagObj, keepProps); }); } }); 

你不应该改变标签的types,而应该改变标签的风格(或者是用特定的id来标记标签)。改变文档的元素来应用风格的改变并不是一个好习惯。 尝试这个:

 $('a.change').click(function() { $('p#changed').css("font-weight", "bold"); }); <p id="changed">Hello!</p> <a id="change">change</a> 

我注意到第一个答案并不是我所需要的,所以我做了一些修改,并且认为我会把它发回到这里。

改进的replaceTag(<tagName>)

replaceTag(<tagName>, [withDataAndEvents], [withDataAndEvents])

参数:

  • tagName: String
    • 标签名称,如“div”,“span”等
  • withDataAndEvents: Boolean
    • “一个布尔值,指示事件处理程序是否应该与元素一起复制。从jQuery 1.4开始,元素数据也将被复制。 信息
  • deepWithDataAndEvents: Boolean
    • 布尔值,指示是否应复制克隆元素的所有子项的事件处理程序和数据。 默认情况下,它的值匹配第一个参数的值(默认为false)

返回:

一个新创build的jQuery元素

好的,现在我知道这里有几个答案,但是我自己再写一遍。

在这里,我们可以用我们使用克隆的方式replace标签。 我们使用.clone()和withDataAndEventsdeepWithDataAndEvents相同的语法来复制节点的数据和事件(如果使用的话)。

例:

 $tableRow.find("td").each(function() { $(this).clone().replaceTag("li").appendTo("ul#table-row-as-list"); }); 

资源:

 $.extend({ replaceTag: function (element, tagName, withDataAndEvents, deepWithDataAndEvents) { var newTag = $("<" + tagName + ">")[0]; // From [Stackoverflow: Copy all Attributes](http://stackoverflow.com/a/6753486/2096729) $.each(element.attributes, function() { newTag.setAttribute(this.name, this.value); }); $(element).children().clone(withDataAndEvents, deepWithDataAndEvents).appendTo(newTag); return newTag; } }) $.fn.extend({ replaceTag: function (tagName, withDataAndEvents, deepWithDataAndEvents) { // Use map to reconstruct the selector with newly created elements return this.map(function() { return jQuery.replaceTag(this, tagName, withDataAndEvents, deepWithDataAndEvents); }) } }) 

请注意,这不会replace选定的元素,它会返回新创build的元素。

是否有一个特定的原因,你需要改变标签? 如果你只是想让文字更大,改变p标签的CSS类将是更好的方法。

像这样的东西:

 $('#change').click(function(){ $('p').addClass('emphasis'); }); 

我想出了一种方法,使用jQuery对象的string表示forms,并使用正则expression式和基本JavaScriptreplace标记名称。 你不会丢失任何内容,也不必循环每个属性/属性。

 /* * replaceTag * @return {$object} a new object with replaced opening and closing tag */ function replaceTag($element, newTagName) { // Identify opening and closing tag var oldTagName = $element[0].nodeName, elementString = $element[0].outerHTML, openingRegex = new RegExp("^(<" + oldTagName + " )", "i"), openingTag = elementString.match(openingRegex), closingRegex = new RegExp("(<\/" + oldTagName + ">)$", "i"), closingTag = elementString.match(closingRegex); if (openingTag && closingTag && newTagName) { // Remove opening tag elementString = elementString.slice(openingTag[0].length); // Remove closing tag elementString = elementString.slice(0, -(closingTag[0].length)); // Add new tags elementString = "<" + newTagName + " " + elementString + "</" + newTagName + ">"; } return $(elementString); } 

最后,你可以像下面这样replace现有的对象/节点:

 var $newElement = replaceTag($rankingSubmit, 'a'); $('#not-an-a-element').replaceWith($newElement); 

这是我的解决scheme。 它允许在标签之间切换。

 <!DOCTYPE html> <html> <head> <title></title> <script src="jquery-1.11.3.js"></script> <script type="text/javascript"> function wrapClass(klass){ return 'to-' + klass; } function replaceTag(fromTag, toTag){ /** Create selector for all elements you want to change. * These should be in form: <fromTag class="to-toTag"></fromTag> */ var currentSelector = fromTag + '.' + wrapClass(toTag); /** Select all elements */ var $selected = $(currentSelector); /** If you found something then do the magic. */ if($selected.size() > 0){ /** Replace all selected elements */ $selected.each(function(){ /** jQuery current element. */ var $this = $(this); /** Remove class "to-toTag". It is no longer needed. */ $this.removeClass(wrapClass(toTag)); /** Create elements that will be places instead of current one. */ var $newElem = $('<' + toTag + '>'); /** Copy all attributes from old element to new one. */ var attributes = $this.prop("attributes"); $.each(attributes, function(){ $newElem.attr(this.name, this.value); }); /** Add class "to-fromTag" so you can remember it. */ $newElem.addClass(wrapClass(fromTag)); /** Place content of current element to new element. */ $newElem.html($this.html()); /** Replace old with new. */ $this.replaceWith($newElem); }); /** It is possible that current element has desired elements inside. * If so you need to look again for them. */ replaceTag(fromTag, toTag); } } </script> <style type="text/css"> section { background-color: yellow; } div { background-color: red; } .big { font-size: 40px; } </style> </head> <body> <button onclick="replaceTag('div', 'section');">Section -> Div</button> <button onclick="replaceTag('section', 'div');">Div -> Section</button> <div class="to-section"> <p>Matrix has you!</p> <div class="to-section big"> <p>Matrix has you inside!</p> </div> </div> <div class="to-section big"> <p>Matrix has me too!</p> </div> </body> </html>