word-relay 예제 따라하기 - html 태그 선택하기 편

Nian·2022년 5월 1일
0

참조

  1. 이 글은 "Let's Get IT 자바스크립트 프로그래밍"의 예제를 따라면서 자습하는 글입니다.
  2. 별도로 인터넷에서 찾아 작성한 예제도 포함될 수 있습니다. (출처 명시)

자바스크립트로 HTML 태그를 가져오기

책에 따르면 보통 자바스크립트에서 HTML 태그, class, id를 가져오는 것을 선택 한다고 표현함.
이에 해당되는 함수는

  • document.querySelector
  • document.querySelectorAll
  • document.getElementById
  • document.getElementByClass

등이 있다.
현재 보고 있는 페이지에서는 docuement.querySelector만 있기 때문에 나머지는 다른 책과 인터넷에서 찾기로 했다.

1. document.querySelector()

  • 형식 : document.querySelector('선택자')
    선택에 대한 예시는 다음과 같다.
    • HTML태그 : document.querySelector('HTML태그')
    • class명 : document.querySelector('.class명')
    • id명 : document.querySelector('#id명')

  • 예시 1
    * 출처 : Let's Get IT 자바스크립트 프로그래밍
<body>
	<div><span id="order">1</span>번째 참가자</div>
    <div>제시어: <span id="word"></span></div>
    <input type="text">
    <button>입력</button>
    <button>버튼 2</button>
    <button>버튼 3</button>
    <script>
    	const $input = document.querySelector('input');
        console.log($input);
    </script>
</body>
  • 예시 2
    * 출처 : 자바스크립트 코드레시피 278
<div id="foo"></div>
<ul class="list">
	<li class="item"></li>
    <li class="item"></li>
    <li class="item"></li>
</ul>
<script>
	document.querySelector('#foo')
</script>
  • 특정 name, id, class를 제한하지 않고 css 선택자를 사용이 가능.
  • 같은 id와 class인 경우, 최상단 요소만 포함함.
  • list 클래스 내 두번째 item 클래스를 선택하고 싶다면 아래처럼 가능
    document.quertSelector('.item .item:nth-child(2))

2. document.qeurySelectorAll()

  • 형식 : document.querySelectorAll('선택자')

  • 주의 : document.querySelector()와 달리 선택자를 가진 모든 요소를 가져와 적용시킨다.

  • 예시 1

<!doctype html>
<html lang="ko">
	<head>
    	<meta charset="utf-8">
        <title>Javascript</title>
    </head>
    <body>
    	<p class="abc">Lorem Ipsum Dolor</p>
        <p class="abc">Lorem Ipsum Dolor</p>
        <p class="abc">Lorem Ipsum Dolor</p>
        <script>
        	var jb = document.querySelectorAll('.abc');
            for (var i = 0; i < jb.length; i++) {
            	jb[i].style.color = 'red';
            }
        </script>
    </body>
</html>

3. document.getElementById()

  • 형식 : document.getElementById('id명')
  • 주의사항
  1. 셀렉터명이 아닌 ID명만 전달. #을 빼고 작성해야 함.
  2. ID값은 문서 전체에서 유일해야 함.
  3. 대소문자를 구분함.

<html>
<head>
	<title>getElementById 예제</title>
</head>
<body>
	<p id="para">어떤 글</p>
    <button onclick="changeColor('blue');">blue</button>
    <button onclick="changeColor('red');">red</button>
</body>
<script>
	function changeColor(newColor) {
    	var elem = document.getElementById('para');
        elem.style.color = newColor;
	}
</script>
</html>

4. document.getElementByClassName()

  • 형식 : `document.getElementByClassName('class명')
  • 참조
  1. getElementById와 다르게 클래스명과 일치하는 요소 모두 가져온다.
  2. class명만 전달. .를 빼고 작성해야 함.
<!doctype html>
<html>
<head>
<style>
div {
	border: 1px solid black;
    margin: 5px;
}
</style>
</head>
<body>

<div class="example">
	<p>P element in first div with class="example". Div's index is 0.</p>
</div>


<div class="example color">
	<p>P element in first div with class="example color". Div's index is 1.</p>
</div>

<div class="example color">
	<p>P element in second div with class="example color". Div's index is 1.</p>

<p>Click the button to change the background color of the first div element with the classes "example" and "color".</p>

<button onclick="myFunction()">Try it</button>

<p><strong>Note : </strong> The getElementsByClassName() methode is not supported in Internet Explorer 8 and earlier versions.</p>

<script>
function myFunction() {
	var x = document.getElementsByClassName("example color");
    x[0].style.backgroundColor = 'red';
}
</script>

</body>
</html>
profile
무언가를 하고 있지만, 잘 안될 수 있습니다.

0개의 댓글

관련 채용 정보