programing

jQuery를 사용하여 하나의 태그를 다른 태그로 바꾸기

subpage 2023. 11. 5. 14:40
반응형

jQuery를 사용하여 하나의 태그를 다른 태그로 바꾸기

목표:

jQuery를 사용하여 다음과 같은 경우를 모두 대체하려고 합니다.

<code> ... </code>

다음 항목 포함:

<pre> ... </pre>

내 솔루션:

저는 다음과 같은 것들을 알아냈습니다.

$('code').replaceWith( "<pre>" + $('code').html() + "</pre>" );

솔루션의 문제점:

그러나 문제는 (두 번째, 세 번째, 네 번째 등) "코드" 태그 사이의 모든 것을 첫 번째 "코드" 태그 사이의 내용으로 대체하고 있다는 것입니다.

예.

<code> A </code>
<code> B </code>
<code> C </code>

된다

<pre> A </pre>
<pre> A </pre>
<pre> A </pre>

저는 "이것"과 어떤 기능을 사용해야 한다고 생각합니다만, 저는 아직도 배우고 있고 해결책을 어떻게 짜맞추는지 잘 모르겠습니다.

다음에 함수를 전달할 수 있습니다.[docs]

$('code').replaceWith(function(){
    return $("<pre />", {html: $(this).html()});
});

기능 안에,this현재 처리된 상태를 가리킵니다.code요소.

데모

업데이트 : 성능 차이는 크지 않지만, 만약에code요소에는 다른 HTML 자식이 있습니다. 자식을 직렬화하는 대신 추가하는 것이 더 정확하게 느껴집니다.

$('code').replaceWith(function(){
    return $("<pre />").append($(this).contents());
});

이것이 훨씬 더 좋습니다.

$('code').contents().unwrap().wrap('<pre/>');

인정하건대 펠릭스 클링의 해결책은 대략 두 배나 빠릅니다.

항상 첫번째를 얻는 것이 맞습니다.code의 내용은, 왜냐하면$('code').html()사용하는 곳에 상관없이 항상 첫 번째 요소를 참조합니다.

대신 모든 요소를 반복하고 각 요소를 개별적으로 변경하는 데 사용할 수 있습니다.

$('code').each(function() {
    $(this).replaceWith( "<pre>" + $(this).html() + "</pre>" );
    // this function is executed for all 'code' elements, and
    // 'this' refers to one element from the set of all 'code'
    // elements each time it is called.
});

시도해 보기:

$('code').each(function(){

    $(this).replaceWith( "<pre>" + $(this).html() + "</pre>" );

});

http://jsfiddle.net/mTGhV/

이건 어때?

$('code').each(function () {
    $(this).replaceWith( "<pre>" + $(this).html() + "</pre>" );
});

펠릭스의 답변을 토대로.

$('code').replaceWith(function() {
    var replacement = $('<pre>').html($(this).html());
    for (var i = 0; i < this.attributes.length; i++) {
        replacement.attr(this.attributes[i].name, this.attributes[i].value);
    }
    return replacement;
});

이것은 의 속성을 재현할 것입니다.code교체 시 태그pre꼬리표를 붙이기

편집: 이것은 심지어 그것들을 대체할 것입니다.code내부에 있는 태그innerHTML타의code꼬리표를 붙이기

function replace(thisWith, that) {
    $(thisWith).replaceWith(function() {
        var replacement = $('<' + that + '>').html($(this).html());
        for (var i = 0; i < this.attributes.length; i++) {
            replacement.attr(this.attributes[i].name, this.attributes[i].value);
        }
        return replacement;
    });
    if ($(thisWith).length>0) {
        replace(thisWith, that);
    }
}

replace('code','pre');

jQuery 1.4.2 기준:

$('code').replaceWith(function(i,html) {
  return $('<pre />').html(html);
});​

그런 다음 새 요소를 선택할 수 있습니다.

$('pre').css('color','red');

출처 : http://api.jquery.com/replaceWith/ # comment-45493689

jsFiddle: http://jsfiddle.net/k2swf/16/

바닐라 자바스크립트를 사용한다면 다음과 같습니다.

  • 새 요소 만들기
  • 기존 요소의 자식을 새 요소로 이동
  • 이전 요소 앞에 새 요소 삽입
  • 기존 요소 제거

다음은 이 프로세스와 동등한 jQuery입니다.

$("code").each(function () {
    $("<pre></pre>").append(this.childNodes).insertBefore(this);
    $(this).remove();
});

jsperf URL은 다음과 같습니다.
http://jsperf.com/substituting-one-tag-for-another-with-jquery/7

PS: 를 사용하는 모든 솔루션.html()아니면.innerHTML파괴적입니다

짧고 쉬운 또 다른 방법:

$('code').wrapInner('<pre />').contents();

여기에 제시된 모든 답변은 (질문 예에서 알 수 있듯이) 태그에 속성이 없다고 가정합니다.승인된 답변이 실행되는 경우:

<code class='cls'>A</code>

대신에

<pre>A</pre>

태그 교체가 의미하는 속성을 유지하려면 어떻게 해야 합니까? 이것이 해결책입니다.

$("code").each( function(){
    var content = $( "<pre>" );

    $.each( this.attributes, function(){ 
         content.attr( this.name, this.value );
    } );

    $( this ).replaceWith( content );
} );
$('code').each(function(){
    $(this).replaceWith( "<pre>" + $(this).html()  + "</pre>" );
    });

가장 좋고 깨끗한 방법.

당신은 jQuery의 html 기능을 사용할 수 있습니다.아래는 코드의 모든 속성을 유지하면서 코드 태그를 사전 태그로 대체하는 예제입니다.

    $('code').each(function() {
        var temp=$(this).html();
        temp=temp.replace("code","pre");
        $(this).html(temp);
    });

이는 이전 태그의 모든 속성을 유지하면서 스왑해야 하는 HTML 요소 태그 집합에서 작동할 수 있습니다.

만든jquery플러그인, 속성도 유지합니다.

$.fn.renameTag = function(replaceWithTag){
  this.each(function(){
        var outerHtml = this.outerHTML;
        var tagName = $(this).prop("tagName");
        var regexStart = new RegExp("^<"+tagName,"i");
        var regexEnd = new RegExp("</"+tagName+">$","i")
        outerHtml = outerHtml.replace(regexStart,"<"+replaceWithTag)
        outerHtml = outerHtml.replace(regexEnd,"</"+replaceWithTag+">");
        $(this).replaceWith(outerHtml);
    });
    return this;
}

용도:

$('code').renameTag('pre')

언급URL : https://stackoverflow.com/questions/7093417/using-jquery-to-replace-one-tag-with-another

반응형