Front-End/Javascript
JavaScript: html 가져와서 내용 확인 ex: document.querySelector()
brightGarden02
2023. 1. 13. 08:46
js에서 html을 가져와서 내용을 확인하고 싶을 경우
여러가지 방법이 있겠지만 몇가지 방법을 소개하고자 한다.
document.getElementById();
document.getElemensByClassName();
document.querySelector();
document.getElementById(); // html에서 id 값을 가져오고 싶을 경우 사용
document.getElemensByClassName(); // html에서 특정한 element 값으로 되어 있는 여러 element를 한번에 가져오고 싶을 경우 사용
document.getElementsByTagName(); // tag name에 대해서 array로 값을 가져옴
document.querySelector(); // element를 검색할 수 있으므로 많이 사용하는 함수
document.querySelector(".hello h1"); // html에 class이름이 hello에서 tag name이 h1인 값을 가져오고 싶을 경우 사용
여러개 있을 경우 첫번째 값만 가져옴.
document.querySelector(".hello h1:first-child"); // css selecto를 사용하여 찾기 때문에 .을 사용
document.querySelectorAll(".hello h1"): document.querySelector(".hello h1") 함수에서 값 여러개를 Array로 가져옴
아래 두 줄은 같은 내용임: id가 hello인 값 가져옴
document.querySelector("#hello");
document.getElementById("hello");
참고:
바닐라 JS로 크롬 앱 만들기 -노마드 코더-