JavaScript 11. DOM 셀렉터와 DOM 이벤트

Yura·2021년 10월 30일
0

JavaScript_Basic

목록 보기
11/28
post-thumbnail

DOM (Document Object Model)

DOM은 화면에 보이는 HTML 코드를 DOM Tree(태그의 뼈대)로 구성한 객체지향 모델이다. 브라우저는 HTML코드를 해석해서 계층화된 Tree 형태의 구조화된 Node들을 가지고 있는 DOM을 생성한다. DOM은 JS가 HTML 소스에 접근하여 내용을 가져오거나 변경하기 위한 통로(인터페이스)의 역할을 한다.

  • document.querySelector() 와 같은 형태
  • Object란? 어떤 데이터를 저장하는 배열과 같은 그릇(컨테이너)라고 할 수 있다.
    (추후 자세히 포스팅 할 예정)

Dom Selector (document객체의 다양한 메소드)

1. CSS 방식으로 가져오는 querySelector - ES6 문법(IE8부터 지원)

  • document.querySelector() : 태그명, 아이디(#), 클래스(.) 선택 - 1개만 document.querySelector("#selector") //아이디명이 selector인 태그 가져오기 document.querySelector('[data-name='box']'); //특정 속성을 가진 태그 가져오기 document.querySelector("#selector").style.background = "gray"; //선택한 아이디의 css 스타일 변경
  • document.querySelectorAll() : 복수의 css태그명 및 클래스를 NodeList로 리턴
    document.querySelectorAll('#selector>li'); //selector 아이디 안에 있는 모든 li 태그 배열형식으로 가져오기

2. HTML 태그를 가져오는 getElement - ES5 이하 문법

  • document.getElementById() : 아이디 선택 - 1개만
    document.getElementById('box');
  • document.getElementsByClassName() : 복수의 클래스를 HTMLCollection으로 리턴
    document.getElementByClassName("box"); //한가지 클래스도 html컬렉션으로 리턴됨
  • document.getElementsByTagName() : 복수의 태그를 HTMLCollection으로 리턴
    document.getElementByTagName("h1"); //모든 h1 태그를 html컬렉션으로 리턴

3. HTML 태그 속성을 가져오거나 변경하는 Attribute

(HTML 속성 = src, href 등)

  • 태그명.getAttribute() : 속성값 반환
    img.getAttribute("src"); //img태그의 src속성 가져오기
  • 태그명.setAttribute(속성명, 세팅값) : 속성값 변경
    img.setAttribute("src","./imges/main.jpg"); //img태그의 src속성을 main 이미지로 변경하기
  • 태그명.removeAttribute() : 속성값 삭제
    input.removeAttribute("onclick"); //input태그의 onclick속성 삭제
  • 태그명.hasAttribute() : 특정 속성을 가지고 있는지 검사
    console.log($cont.hasAttribute("id"));

4. CSS 속성을 변경하는 Property

(css 속성 = width, height, color, line-height, background-color 등)

  • 태그명.setProperty(속성명, 세팅값) : 속성값 변경
    $cont.style.setProperty('width','300px');

DOM Event

  • 변수명or선택자 .addEventListener("이벤트",콜백함수,이벤트방식) : 요소에 이벤트 핸들러를 연결해주는 메소드
    - 이벤트종류 : click, change, focus, keydown, keyup, load, mousedown, mouseout, mouseover, mousemove, mouseup, select, touchstart 등...
    - 이벤트방식(생략가능) : false는 bubbling(자식에서 부모로 이벤트 전달,기본값) / true는 capturing(부모에서 자식으로 이벤트가 전달)
<script>
  let container = document.getElementById("container");
  container.addEventListener("click", function(){},false);
  // container 변수를 클릭했을 때 함수이벤트를 실행한다. 
  // function() : 익명함수 형태의 이벤트핸들러도 가능
  
  document.getElementById('thmb').addEventListener('click', fuction(){console.log("썸네일");})
  // thmb아이디를 클릭했을 때 콘솔에 출력되는 이벤트 실행
</script>
  • stopPropagation() : 이벤트 발생 시 동일한 이벤트를 가진 요소간의 흐름을 막는다.
  • preventDefalut() : 발생 이벤트(함수)의 기본값을 막는다.
profile
가치와 의미를 쫓는 개발자 되기✨

0개의 댓글