programing tip

jQuery에서 div 내부의 모든 HTML을 제거하고 싶습니다.

itbloger 2020. 10. 28. 07:49
반응형

jQuery에서 div 내부의 모든 HTML을 제거하고 싶습니다.


div가 있고 해당 div 내부의 모든 HTML을 제거하고 싶습니다.

어떻게 할 수 있습니까?


함수 를 사용하려고 합니다.

$('#mydiv').empty();

나는 생각하지 않는다 empty()또는 html()당신을 위해 무엇을 찾고 있습니다. 나는 당신이 strip_tagsPHP에서 와 같은 것을 찾고 있다고 생각합니다 . 이렇게하려면 다음 기능을 추가해야합니다.

jQuery.fn.stripTags = function() {
    return this.replaceWith( this.html().replace(/<\/?[^>]+>/gi, '') );
};

이것이 HTML이라고 가정하십시오.

<div id='foo'>This is <b>bold</b> and this is <i>italic</i>.</div>

그리고 다음을 수행합니다.

$("#foo").stripTags();

결과는 다음과 같습니다.

<div id='foo'>This is bold and this is italic.</div>

또 다른 방법은 html을 빈 문자열로 설정하는 것입니다.

$('#mydiv').html('');

var htmlJ = $('<p><span>Test123</span><br /><a href="http://www.google.com">goto Google</a></p>');
console.log(htmlJ.text()); // "Test123goto Google"

  function stripsTags(text)
  {
    return $.trim($('<div>').html(text).text());
  }

이와 같은 html이 있다고 가정하십시오.

<div class="prtDiv">
   <div class="first">
     <div class="hello">Hello</div>
     <div class="goodbye">Goodbye</div>
  </div>
</div>

"첫 번째"div 아래의 모든 html을 영구적으로 제거하려는 경우. 그냥 사용하세요

$('.first').empty();

결과는 다음과 같습니다

<div class="prtDiv">
   <div class="first">

  </div>
</div>

임시로 (다시 추가하고 싶다면) detach ()를 시도 할 수 있습니다.

$('.first').detach();

참고 URL : https://stackoverflow.com/questions/652917/in-jquery-i-want-to-remove-all-html-inside-of-a-div

반응형