JS 관련/JQuery
[jQuery] replaceWith(), replaceAll()
씨네
2022. 2. 22. 12:58
728x90

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="resources/js/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("button:first").click(function(){
// target.replaceWith(newContent); // -> 여기서 사용되는 뉴컨텐트는 htmlString, Element, Array, jQuery
$("p").replaceWith("<p><b>replaceWith</b></p>");
});
$("button:last").click(function(){
// newContent.replaceAll(target); // api 찾아보자
$("<p><b>replaceAll</b></p>").replaceAll("p");
});
});
</script>
</head>
<body>
<div>
<p>DOM 대체</p>
</div>
<button>바꾸기 (replaceWith)</button>
<br>
<button>바꾸기 (replaceAll)</button>
</body>
</html>

$("button:first").click(function(){
$("p").replaceWith("<p><b>replaceWith</b></p>");
});

첫번쨰 버튼을 누르면 <p>태그 영역을 <p><b>replaceWith</b></p>로 대체합니다.

$("button:last").click(function(){
$("<p><b>replaceAll</b></p>").replaceAll("p");
});

두번째 버튼을 누르면 <p><b>replaceAll</b></p>로 대체합니다.

728x90