자바스크립트

document.createElement

사라링 2012. 6. 14. 13:28


document.createElement

« Gecko DOM Reference

요약

지정된 태그이름을 가지는 엘리먼트를 생성합니다.

문법

엘리먼트 = document.createElement(태그이름);
  • 엘리먼트 생성된 엘리먼트 객체입니다.
  • 태그이름 생성할 엘리먼트의 종류를 지정하는 문자열입니다. 생성된 엘리먼트의 nodeName 속성은 태그이름에 지정된 값으로 초기화됩니다.

예제

이 예제는 새로운 <div> 엘리먼트를 생성한 후, id가 "org_div1" 인 엘리먼트 앞에 추가합니다:

<html>
<head>
<title>||엘리먼트 사용하기||</title>
</head>

<script type="text/javascript">
var my_div = null;
var newDiv = null;

function addElement()
{
  // 새로운 div 엘리먼트를 만들고
  // 내용을 작성합니다.
  newDiv = document.createElement("div");
  newDiv.innerHTML = "<h1>안녕! 반가워!</h1>";

  // 생성된 엘리먼트를 추가합니다.
  my_div = document.getElementById("org_div1");
  document.body.insertBefore(newDiv, my_div);
}

</script>

<body onload="addElement()">
<div id='org_div1'> 위의 문장은 동적으로 만들어 진 것입니다.</div>
</body>
</html>

참고 사항

기본값이 있는 잘 알려진 특성(attributes)들은 자동으로 생성되어 엘러먼트에 특성노드로 추가됩니다.

qualified 이름과 네임스페이스 URI를 갖는 엘리먼트를 만들 경우에는 createElementNS 메서드를 사용합니다.

Gecko 엔진의 createElement 구현은 XUL과 XHTML 문서에 대한 DOM 규약을 따르지 않습니다: localNamenamespaceURInull로 설정되지 않습니다. 자세한 사항은 bug 280692 를 참고하세요.




== 추가

Use jQuery objects to build up your table instead of using string concatenation.  How many time have you seen code similar to the following to build up a table?

        $(function () {

            var content = '';
            content += '<div id="tableWrap">';
            content += '<table id="basicTable">';

            for (var i = 0; i < 200; i++) {


                content += '<tr>';
                content += '<td>';
                content += i;
                content += '</td>';
                content += '<td>';
                content += 200 - i;
                content += '</td>';
                content += '</tr>';
            }

            content += '</table>';
            content += '</div>';

            $('body').append(content);
        });

Let's use jQuery's built in ability to build up the objects and take a look at how we could write this differently below.

        $(function () {

            var $wrap = $('<div>').attr('id', 'tableWrap');

            var $tbl = $('<table>').attr('id', 'basicTable');

            for (var i = 0; i < 200; i++) {

                $tbl.append(
                            $('<tr>')
                                    .append($('<td>').text(i),
                                            $('<td>').text(200 - i))
                           );
            }

            $wrap.append($tbl);
            $('body').append($wrap);
        });

View the live code here!