개발하는 루루언니

노드조작하기 : textContent , innertext , innerHTML 본문

컴퓨터 정보/javascript

노드조작하기 : textContent , innertext , innerHTML

혜닝혜루 2022. 11. 30. 12:04
728x90
반응형

 

 

 

document.querySelector( " #태그명 " ) ex ) p 

document.getElementById(" 아이디값 " ) ex ) title 


 

 <h1 id="title">h1 <span style="display: none;">javascript</span></h1>
  <script>
    const pEl = document.getElementById("title")
    console.log(pEl.textContent)
  </script>

 

textContent : 

 

 

 

textContent는 태그는 가져오지 않고 text만 가져온다. 근데 css로 span태그안에 javascript를 가렸는데도

콘솔창에는 출력이 되는걸 알 수 있다.

 

 <h1 id="title">h1 <span style="display: none;">javascript</span></h1>
  <script>
    const pEl = document.getElementById("title")
    
    pEl.textContent ='안녕하세요'

 

이렇게 직접 변수명.textContent = ' 글자 ' 입력을 해서 직접 글자를 출력할 수도있다.


innerText :

 <h1 id="title">h1 <span style="display: none;">javascript</span></h1>
  <script>
    const pEl = document.getElementById("title")
    
    console.log(pEl.textContent)
    console.log(pEl.innerText)
  </script>

 

innerText를 하면 내가 css 숨긴 자바스크립트는  출력해도  보이지 않게 된다. 

 

    pEl.innerHTML ='안녕하세요'

이렇게 변수명에 직접 text를 입력해도 출력이 된다.

 

 

 


    document.querySelector('#textContent').textContent ='hello textContent';
    document.querySelector('#innerText').innerText ='<strong> hello textContent </strong>';
    document.querySelector('#innerHTML').innerHTML ='<strong> hello textContent </strong>';

여기서 주의깊게 볼건 innerHTML 은 태그속성을 포함한다는것이다.

innerText 는 strong태그를 그대로 문자열로 반환한다.

 

728x90