HTML in JS

장돌뱅이 ·2022년 1월 22일
0
  • js는 html에 이미 연결되어 있기 때문에 html에 접근하고 읽을 수 있다.
    document = js관점에서 html을 의미하는 object, js에서 html 항목에 접근하는 방법이다.

    • js에서 html 항목에 접근하는 방법
      1.document에서 항목들을 가져오고 검색하기
      2.document 항목들을 변경하는 것
  • document의 함수 중에는 getElementById 라는 함수가 있는데, HTML에서 id를 통해 element를 찾아준다. element를 찾고 나면, JS로 해당 HTML의 무엇이든 바꿀 수 있다.

  • getElementById() : 하나의 값 반환

  • getElementsByClassName() : 주로 많은 element를 한번에 가져올때 씀(array 반환)

  • getElementsByTagName("h1") : name을 할당할 수 있음(array 반환)

  • document.querySelector(".hello h2") : element를 CSS selector방식으로 검색할 수 있음(hello 클래스의 h2 가져오기), 단 하나의 element를 return해줌,첫번째 element만 가져옴

  • 조건에 맞는 요소 다 가져오고 싶으면 querySelectorAll ⇒ 요소 h1이 들어있는 array를 가져다 줌

  • querySelector("#hello); 와 getElementById("hello"); 는 같은 일을 하지만, 후자는 하위요소 가져오는 것을 못하므로 전자만 사용한다.

console.log(title); : title요소를 보여줌
console.dir(title); : 요소 내부를 보여줌

0개의 댓글