• 회원가입
  • 로그인
  • 구글아이디로 로그인

[HTML_CSS] JQ - replaceWith() 메서드 ★ - 선택요소 내용를 새 내용으로 대체/변경 (= replaceWith메서드 = 리플레이스위드 메서드) ※ 이미지 클릭 시 HTML 태그로 변경

목차
  1. replaceWith() 예제 - 지정 글자로 요소 내용 변경
  2. replaceWith() 정의
  3. replaceWith() 구문
  4. replaceWith() 예제 - 함수 사용해 요소 내용 변경
  5. replaceWith() 예제 - 이미지 클릭 시 HTML 태그로 변경

 

replaceWith() 예제 - 지정 글자로 요소 내용 변경

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

  $("button").click(function(){

    $("p:first").replaceWith("Homzzang.com");

  });

});

</script>


<p>홈짱닷컴</p>

<p>홈페이지 제작관리 강의</p>


<button>클릭</button>

 

결과보기

 

replaceWith() 정의

 

선택 요소의 내용을 지정 내용으로 대체.

 


 

더 많은 예제 보기: https://api.jquery.com/replacewith/

 

 

replaceWith() 구문

 

$(selector).replaceWith(newContent)

또는,

$(selector).replaceWith(function(index))

 


[매개변수]

 

newContent

기존 내용을 대체할 새 내용 지정. (HTML 태그 포함 가능) 

※ 가능값 종류

  • HTML 요소들
  • jQuery 객체들
  • DOM 요소들

 

function(index)

기존 내용을 대체할 새 내용을 반환하는 함수 지정.

 

index

요소집합에서 요소의 색인 위치 반환

 

 

replaceWith() 예제 - 함수 사용해 요소 내용 변경

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

  $("button").click(function(){

    $("p").replaceWith(function(n){

      return "<h3>요소 색인번호: " + n + "</h3>";

    });

  });

});

</script>


<h1>홈짱닷컴 Homzzang.com</h1>

 

<p>코딩언어 강의</p>

<p>그누보드 강의</p>

<p>서버관리 강의</p>

 

<button>클릭</button>

 

결과보기

 

replaceWith() 예제 - 이미지 클릭 시 HTML 태그로 변경

 

<script src="http://code.jquery.com/jquery-latest.min.js"></script>


<script>

$(document).on('click','.box',function(e){

    $(this).find('img.hz').replaceWith('<p">홈짱닷컴 Homzzang.com</p>');

});

</script>


<div class="box">

    <img src="https://i.imgur.com/WfW5mBC.png" alt="홈짱" class="hz">

</div>


결과보기

 


분류 제목
HTML_CSS JQ - val() 메서드 ★★★ - value속성 값설정/값반환 (= val메서드 = 밸메서드) ※ 밸류메…
HTML_CSS JQ - width() 메서드 ★★★ - 요소 너비 설정/반환. (= width메서드 = 위드스메서드)
HTML_CSS JQ - wrap() 메서드 ★ - 선택요소를 지정 부모요소로 감싸기. (= wrap메서드 = 랩메서드)
HTML_CSS JQ - wrapAll() 메서드 - 선택요소 모두를 한번에 지정 요소로 감싸기. (= wrapAll메서드 …
HTML_CSS JQ - wrapInner() 메서드 - 선택요소 안 내용을 지정 요소로 감싸기 (= wrapInner메서드…
3/3
목록
찾아주셔서 감사합니다. Since 2012