다음 내용은 O`relly 시리즈 중 하나인 《자바스크립트 완벽 가이드》(인사이트)의 한국어판 435페이지를 변용하여 옮긴 것이다. 너무나 알고 싶었던 기능이라서 한참 동안 읽다가 바로 메모하기로 결정!
소스를 보면 다 알 것이므로 설명은 생략한다. 다만, 저 책은 자바스크립트를 공부하고 싶은 사람들에겐 무조건 강추다. 끝.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>textNode Test</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <meta name="author" content="ahw" /> <meta name="keywords" content="textNode" /> <meta name="description" content="textNode control example." /> <script type="text/javascript"> //이 함수는 Node n을 전달인자로 받고, 이 노드를 HTML <strong> 태그를 표현하는 Element 노드로 교체한 후 기존 노드를 새로 만든 <strong> 엘리먼트의 자식으로 만든다. function emStrongly(n){ if (typeof n == "string") n = document.getElementById(n); //노드를 조사한다. var s = document.createElement("strong"); //새로운 <strong> 엘리먼트를 생성. var parent = n.parentNode; //주어진 노드의 부모를 얻는다. parent.replaceChild(s, n); //주어진 노드를 <strong> 태그로 교체한다. s.appendChild(n); } </script> </head> <body> <!-- 두 개의 샘플 문단 --> <p id="p1">이것은 <i>문단</i> 1입니다.</p> <p id="p2">이것은 <i>문단</i> 2입니다.</p> <!-- emStrongly() 함수를 p1이라는 엘리먼트에 대해 호출하는 버튼 --> <button onclick="emStrongly2('p1');">EmStrongly</button> </body> </html>