더보기
/*
- document 객체
- HTML요소들을 선택, 생성, 삭제 등을 위해 사용하는 객체
- 요소 선택 메소드
- getElementById('아이디명')
- 아이디가 일치하는 요소 하나를 가져옴(최대하나)
- 중복이 불가능해서 element에 s가 붙으면 안됨
- getElementsByClassName('클래스명');
- 클래스명이 일치하는 요소들을 배열로 가져옴
- getElementsByTagName('태그명');
- 태그명이 일치하는 요소들을 가져옴
- getElementsByName('name명');
- 속성 name이 name명과 일치하는 요소들을 배열로 가져옴
- querySelector('선택자');
- 선택자와 일치하는 첫번째 요소를 가져옴(최대하나)
- querySelectorAll('선택자');
- 선택자와 일치하는 요소들을 배열로 가져옴
*/
<body>
<div class="box" id="box1" name="a">박스1</div>
<div class="box" id="box2" name="a">박스2</div>
<div class="box" id="box3" name="b">박스3</div>
<p class="box" id="box4" name="b">박스4</p>
<script>
var box1 = document.getElementById('box1');
console.log('아이디 요소 선택')
console.log(box1);
var boxes = document.getElementsByClassName('box');
console.log('클래스로 요소 선택');
for(var box of boxes){ //배열 for-of가능
console.log(box);
}
var tags= document.getElementsByTagName('p');
console.log('태그로 요소 선택');
for(var box of tags){
console.log(box);
}
var names= document.getElementsByName('a');
console.log('name으로 요소 선택');
for(var box of names){
console.log(box);
}
var box2 = document.querySelector('#box2');
console.log('#box2로 요소 선택');
console.log(box2);
var tags2 = document.querySelectorAll('div'); //쉽게사용하기가 좋음
console.log('div로 요소 선택');
for(var box of tags){
console.log(box);
}
</script>
</body>
'괴발개발 > Javascript+JQuery' 카테고리의 다른 글
JS_location객체 (0) | 2021.06.21 |
---|---|
JS_history객체 (0) | 2021.06.21 |
JS_타이머 기능예제 (0) | 2021.06.21 |
JS_요소선택 (0) | 2021.06.21 |
JS_이벤트(event) (0) | 2021.06.21 |