[JavaScript] innerText, innerHTML, insertAdjacentHTML 정리

seunghwan·2022년 7월 23일
2

JavaScript

목록 보기
3/7
post-thumbnail

innerText

  • HTMLElement.innerText
  • HTMLElement의 렌더링 된 텍스트 값
  • JS에서 쓰는 다양한 값들을 innerText에 넣을 수 있다!
    단, html 태그<>를 그냥 넣을 경우 다음 에러를 만날 수 있다😒
  • 렌더링 된 텍스트 값이기 때문에 변경하더라도 재렌더링이 발생하지는 않는다❗

innerHTML

  • Element.innerHTML
  • Element 내에 포함된 html을 가져온다
  • 출력시 해당 요소의 html 구조가 그대로 다 출력된다
  • innerHTML을 변경하면 DOM 렌더링 시 반영되어 그려진다
  • 단순 Text 삽입 시에는 사용하지 않는 것이 좋다
    왜❓ 잠재적인 보안 위험(XSS)이나, 성능 이슈(불필요한 파싱) 때문

    요소에서 단순 텍스트를 조작할 때는 innerText나 innerHTML보다
    textContent 속성을 활용하는 것이 좋다

insertAdjacentHTML

  • Element.insertAdjacentHTML("들어갈 위치", "html코드 문자열")
  • html을 인접한(Adjacent) 곳에 삽입하는 메서드
  • 첫번째 인자에 beforeend, afterbegin, beforeend, afterend 중 하나가 들어간다
  • Element에 단순히 html을 추가로 삽입하고 싶을 때, innerHTML 보다
    insertAdjacentHTML를 사용하는 것이 좋다

    작업량이 적어서 innerHTML보다 빠르기 때문👍


예시코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>seunghwan</title>
</head>
<body>
    <section>
        <h2 style="margin-bottom: -1px;">innerText</h2>
        <div class="inner-text" style="width: 300px; border: 2px solid rgb(172, 229, 132); padding: 20px; margin-bottom: 50px;">
        </div>
        
        
        <h2 style="margin-bottom: -1px;">innerHTML</h2>
        <div class="inner-html" style="width: 300px; border: 2px solid rgb(116, 177, 71); padding: 20px; margin-bottom: 50px;">
        </div>
        

        <h2 style="margin-bottom: -1px;">insertAdjacentHTML</h2>
        <div class="insert-adjacent-html" style="width: 300px; border: 2px solid rgb(108, 127, 80); padding: 10px 20px 10px;">
        </div>
    </section>
</body>
</html>

<script>
    // Element 변수 선언
    const IT = document.querySelector('.inner-text'); // innerText
    const IH = document.querySelector('.inner-html'); // innerHTML
    const IAH = document.querySelector('.insert-adjacent-html'); // insertAdjcentHTML

    // [ innerText ]  
    IT.innerText = null;
    IT.innerText = 1;
    IT.innerText = [1,2,3,4,5]; // 1,2,3,4,5
    IT.innerText = {name:"hwan", age:"20"}; // [object Object]
    IT.innerText = "<div>태그는 인식되지 않는다</div>"; // <>가 그대로 텍스트 (렌더링 되지 않기 때문)
    IT.innerText = "innerText는 렌더링 된 텍스트 값";
    
    
    // [ innerHTML ]
    IH.innerHTML = "<div><div><div><div><div><div> innerHTML은 태그를 인식하여 렌더링한다 </div></div></div></div></div>";
    console.log("innerText는 DOM이 렌더링된 이후의 결과를 받아온다 \n => ",IH.innerText);
    console.log("innerHTML은 Element의 하위요소들을 그대로 받아온다 \n => ",IH.innerHTML);
    
    
    // [ insertAdjacentHTML ]
    IAH.innerHTML = "<div>"
                    +"      1" 
                    +"      <div>"
                    +"          2"
                    +"          <div>"
                    +"              3"
                    +"          </div>"
                    +"      </div>"
                    +"</div>"; // 초기값 innerHTML로 셋팅
    IAH.insertAdjacentHTML("beforebegin", "<div> beforebegin : 시작 전에 삽입 </div>");
    IAH.insertAdjacentHTML("afterbegin", "<div> afterbegin : 시작 후에 삽입 </div>");
    IAH.insertAdjacentHTML("beforeend", "<div> beforeend : 종료 전에 삽입 </div>");
    IAH.insertAdjacentHTML("afterend", "<div> afterend : 종료 후에 삽입 </div>");
</script>

jQuery

  • innerText와 innerHTML은 jQuery에서는 사용할 수 없다!

    	$(...).innerText is not a function
    	$(...).innerHTML is not a function
  • insertAdjacentHTML은 잘 동작한다 ⭕

  • innerText , innerHTML
    속성(property)인데 함수(function)라고 착각했다,,,
    정상적으로 잘 동작한다,,😒⭕

    HTMLElement 인터페이스의 속성 → innerText
    Element의 속성 → innerHTML

profile
소소한 개발일지💻

2개의 댓글

comment-user-thumbnail
2022년 7월 25일

innerHTML 못쓰는줄알구 .html() 만 사용했는데 쩔어여👍

1개의 답글