2007년 7월 22일 일요일

document.write없이 html삽입하기

document.write을 사용해서 javascript코드를 삽입하는 방법은 다음의 문제를 가지고 있습니다.
  1. XHTML 모드에서 동작하지 않습니다.
  2. document.write를 써서 추가된 코드는 API를 사용하여 접근할 수 있는 방법이 없습니다.
  3. document.write는 HTML을 노드로 보지 않고 Serialized text로 보는 전혀 다른 관점을 지니고 있습니다.(DOM하고 비교했을 때)
document.write가 아닌 DOM을 이용해서 코드를 삽입하려면 다음의 방법을 선택할 수 있습니다.

  1. 호출할 javascript코드를 페이지에 삽입합니다.
    <scrip type="text/javascript" id="syndication" src="syndication.js"></script>

  2. syndication.js에 다음의 코드를 추가합니다.
    // 삽입할 태그를 DOM을 이용해서 생성합니다.
    var newContent = document.createElement('p');
    newContent.id = 'syndicated-content';
    newContent.appendChild(document.createTextNode('Here is some syndicated content.'));

    var source = document.getElementById('syndication');
    // script태그의 바로 앞쪽에 newContent를 삽입하게 합니다.
    source.parentNode.insertBefore(newContent, source);
2의 코드는 document.write('<p id="syndicated-content">Here is some syndicated content</p>');와 동일한 역할을 합니다.

출처: Insert in place without document.write via Simon Willison’s Weblog

댓글 2개:

  1. 제목에 있는 삽입하기를 삽질하기로 봤다 ㅋㅋㅋ.

    답글삭제
  2. @박서은 - 2007/07/23 02:08
    ^^;;;; 삽질도 많이 한답니다. ㅋ

    답글삭제