이게 가능해?
예:
$('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 태그를 삭제하고 h5로 바꿀 수는 있지만 실제로 HTML 태그를 수정해야합니까?
답변
dom 요소가 생성되면 태그를 변경할 수 없습니다. 다음과 같은 작업을 수행해야합니다.
$(this).replaceWith($('<h5>' + this.innerHTML + '</h5>'));
답변
여러 가지 방법으로 많은 요소를 다룰 확장 기능이 있습니다.
사용법 예 :
기존 클래스 및 속성 유지 :
$('div#change').replaceTag('<span>', true);
또는
기존 클래스 및 속성을 삭제하십시오.
$('div#change').replaceTag('<span class=newclass>', false);
또는
모든 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);
        });
    }
});
답변
태그 유형을 변경하는 대신 태그 스타일 (또는 특정 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])
인수 :
보고:
새로 작성된 jQuery 요소
좋아, 나는 지금 여기에 몇 가지 대답이 있다는 것을 알고 있지만, 나는 이것을 다시 작성하기 위해 나 자신에게 그것을 가져 갔다.
여기서 복제를 사용하는 것과 같은 방식으로 태그를 교체 할 수 있습니다. 우리는 같은 문법 다음과 같다 .clone () 과를 withDataAndEvents하고 deepWithDataAndEvents복사하는 자식 사용하면 노드의 데이터와 이벤트를.
예:
$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);
        })
    }
})
이 점에 유의 대체하지 않습니다 선택한 요소, 그것은 새로 만든 하나를 반환합니다.
답변
아이디어는 요소를 감싸고 내용을 풀어 놓는 것입니다.
function renameElement($element,newElement){
    $element.wrap("<"+newElement+">");
    $newElement = $element.parent();
    //Copying Attributes
    $.each($element.prop('attributes'), function() {
        $newElement.attr(this.name,this.value);
    });
    $element.contents().unwrap();
    return $newElement;
}
샘플 사용법 :
renameElement($('p'),'h5');
답변
jQuery 객체의 문자열 표현을 사용하고 정규 표현식과 기본 JavaScript를 사용하여 태그 이름을 바꾸는 접근법을 생각해 냈습니다. 컨텐츠를 잃어 버릴 필요가 없으며 각 속성 / 속성을 반복 할 필요가 없습니다.
/*
 * 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);
}
마지막으로 다음과 같이 기존 객체 / 노드를 교체 할 수 있습니다.
var $newElement = replaceTag($rankingSubmit, 'a');
$('#not-an-a-element').replaceWith($newElement);
답변
이것이 나의 해결책이다. 태그 사이를 전환 할 수 있습니다.
<!DOCTYPE html>
<html>
<head>
	<title></title>
<script src="https://code.jquery.com/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>
