본문 바로가기
Programming/Javascript

자바스크립트 출력

by Hyun's 2024. 9. 13.

자바스크립트 출력


자바스크립트는 다양한 방법으로 데이터를 출력할 수 있습니다.

  • innerHTML : HTML 요소에 데이터를 삽입할 수 있습니다. (단 보안상의 이유로 textContent, innerText를 사용)
  • document.write() : HTML 문서에 직접 콘텐츠를 삽입하는 메소드입니다. (여러 단점과 위험으로 사용하지 않습니다.)
  • window.alert() : 브라우저에 직접 경고창을 띄어서 데이터를 출력합니다. 비슷한 방식으로 confirm()과 prompt()가 ㅣ있습니다.
  • console.log() : F12 키를 누르면 볼 수 있는 console에 데이터를 출력합니다.

 

innerHTML 사용법

<!DOCTYPE html>
<html>
    <head>
        <title>innerHTML</title>
    </head>
    <body>
        <h1>innerHTML</h1>
        <p id="in"></p>
        
        <script>
            document.getElementById("in").innerHTML = "helloworld";
        </script>
    </body>
</html>

textContent, innerText을 사용하는 방법은 innerHTML 자리를 대체하면 됩니다. 

 

사용자 입력을 직접 삽입하는 경우에는 XSS 공격에 취약하므로 주로 textContent, innerText를 사용합니다.

실행결과는 위 이미지와 같습니다.

document.write() 사용법

<!DOCTYPE html>
<html>
    <head>
        <title>documentwrite</title>
    </head>
    <body>
        <script>
            document.write("<h1>Hello World</h1>");
            document.write("<p style='color:red;'>이 곳은 단락입니다.</p>");
        </script>
    </body>
</html>

코드를 작성하면 위와 같습니다. 

실행결과는 위에 그림과 같습니다. HTML 태그와 CSS도 적용이 가능합니다.

 

document.write()의 단점

  • 페이지 리플레시 : 문서가 이미 로드된 후에 호출되면 페이지의 기존 content는 지워지고 새로운 content로 대체됩니다.
  • 성능 문제 : 페이지의 랜더링을 중단시키는 문제가 발생할 수 있습니다.
  • DOM 조작의 어려움 : DOM에 직접 접근해서 요소를 조작하는 것이 불가능합니다.
  • 보안 문제 : HTML과 자바스크립트를 직접 삽입할 수 있기 때문에 XSS 공격에 취약할 수 있습니다.

 

대안

DOM 조작 : createElement, appendChild, insertBefore

<!DOCTYPE html>
<html>
    <head>
        <title>documentwrite</title>
    </head>
    <body>
        <script>
            const p = document.createElement('p');
            p.textContent = 'hello world';
            document.body.appendChild(p);
        </script>
    </body>
</html>

템플릿 리터럴

<!DOCTYPE html>
<html>
    <head>
        <title>documentwrite</title>
    </head>
    <body>
        <script>
            const h1 = `<h1>hello world</h1>`;
            document.body.innerHTML = h1;
        </script>
    </body>
</html>

 

window.alert() 사용법

브라우저에 경고창을 표시할 수 있습니다. window 객체는 글로벌 범위 객체로 변수, 속성, 메소드는 window 객체에 속하기 때문에 생략이 가능합니다.

<!DOCTYPE html>
<html>
    <head>
        <title>documentwrite</title>
    </head>
    <body>
        <script>
            alert("hello world");
        </script>
    </body>
</html>

위와 같은 화면이 브라우저에 나타나게 됩니다. confirm()과 prompt()를 대신해서 사용할 수 있습니다.

 

confirm() 의 경우

<!DOCTYPE html>
<html>
    <head>
        <title>documentwrite</title>
    </head>
    <body>
        <script>
            if(confirm("hello world")) {
                alert("확인");
            }
            else {
                alert("취소");
            }
        </script>
    </body>
</html>

브라우저 대화 상자에 확인과 취소 버튼이 있습니다. 확인을 클릭하면 true를 반환하고 취소 혹은 닫기를 클릭하면 false를 반환하는 메소드 입니다.

 

prompt() 는 사용자에게 값을 입력받을 수 있습니다.

<!DOCTYPE html>
<html>
    <head>
        <title>documentwrite</title>
    </head>
    <body>
        <script>
            const p = prompt("helloworld", "userinput");
            console.log(p);
        </script>
    </body>
</html>

첫 번째 부분은 화면에 출력할 데이터이고 두 번째 부분은 사용자에게 입력을 받을 상자에 표시하는 부분입니다.

박스에 hi를 입력하고 확인 버튼을 누르면 다음과 같은 결과가 나오는 것을 볼 수 있습니다.

 

console.log() 사용법

<!DOCTYPE html>
<html>
    <head>
        <title>documentwrite</title>
    </head>
    <body>
        <script>
            console.log("hello world");
        </script>
    </body>
</html>

브라우저에 있는 콘솔창에 데이터를 출력할 수 있습니다.

위에 코드를 실행한 결과는 다음과 같습니다.

브라우저 콘솔창에서도 console.log()를 사용할 수 있습니다.

 

 

출처

W3school

 

W3Schools.com

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

'Programming > Javascript' 카테고리의 다른 글

자바스크립트에서 타임리프 사용하기  (1) 2024.10.06
자바스크립트 함수  (0) 2024.09.19
자바스크립트 변수  (0) 2024.09.13
자바스크립트 구문  (0) 2024.09.13
자바스크립트 기초  (0) 2024.09.13