프로그래밍/Javascript

[JAVASCRIPT/자바스크립트] 선택자 / 활용

Rolen 2022. 12. 6. 20:48
Selectors(선택자)

1. $("*")		: 모든 요소

<!DOCTYPE html>
<html>
<head>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
	<script>
	$(document).ready(function(){
	  $("#bt2").click(function(){		// id = b2 를 누르면
	    $("*").hide();			// 모든 요소 숨기기
  });
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Click me to hide paragraphs</button>
<button id = "bt2">Click me to hide paragraphs2222</button>

</body>
</html>

=======================================================================

2. $(this)		: 현재 선택된 HTML요소

<script>
$(document).ready(function(){
  $("button").click(function(){
    $(this).hide();		// 위에서 설정된 요소 숨기기
    $("#p2").hide();		// id = p2 인 요소 숨기기
  });
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p>This is a paragraph.</p>
<p id = "p2">This is another paragraph.</p>

<button>Click me</button>

=======================================================================

3. $("p.intro")	: p태그중에서 intro 클래스를 가진 요소

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){	    // click까지는 이벤트 타입, 이벤트 이름
    $("p.intro").hide();	    // 뒤의 function이 이벤트 핸들러 이벤트 리스너
  });			    // p태그 안의 intro 클래스 요소 숨기기	
});
</script>
</head>
<body>

<h2 class="intro">This is a heading</h2>

<p class="intro">This is a paragraph.</p>
<p class="intro">This is another paragraph.</p>

<button>Click me</button>

=======================================================================

4. $("p:first")	: p태그 중 첫 번째 p 요소

=======================================================================

5. $("ul li:first")	: 첫 번째 ul 태그의 첫 번째 li 요소

<script>
$(document).ready(function(){
  $("button").click(function(){
    $("ul li:first").hide();	// 첫 번째 ul의 첫 번째 li 요소 숨기기
  });
});
</script>
</head>
<body>

<p>List 1:</p>
<ul>
  <li>Coffee</li>
  <li>Milk</li>
  <li>Tea</li>
</ul>

<p>List 2:</p>
<ul>
  <li>Coffee</li>
  <li>Milk</li>
  <li>Tea</li>
</ul>

<button>Click me</button>

=======================================================================

6. $("ul li:first-child")	: 모든 ul의 첫 번째 li 요소

<script>
$(document).ready(function(){
  $("button").click(function(){
    $("ul li:first-child").hide();	// 모든 ul의 첫 번째 li 요소 숨기기
  });
});
</script>
</head>
<body>

<p>List 1:</p>
<ul>
  <li>Coffee</li>
  <li>Milk</li>
  <li>Tea</li>
</ul>

<p>List 2:</p>
<ul>
  <li>Coffee</li>
  <li>Milk</li>
  <li>Tea</li>
</ul>

=======================================================================

7. $("[href]")		: href 속성을 가진 모든 요소  // 속성은 []로 감싼다.

=======================================================================

8. $("a[target='_blank']")	: a 태그에서 target 속성이 _black인 요소
9. $("a[target!='_blank']")	: a 태그에서 target 속성이 _black가 아닌 요소

=======================================================================

10. $(":button")		: 타입이 버튼인 요소

=======================================================================

11. $("tr:even")		: tr요소에서 짝수번째 요소 (index로 파악)
12. $("tr:odd")		: tr요소에서 홀수번째 요소 (index로 파악)

=======================================================================

13. $("div > p")	All <p> elements that are a direct child of a <div> element
                                            ★ direct child : 직계자손 ★

<script>
$(document).ready(function(){
  $("div > span").css("background-color", "yellow");
});
</script>
</head>
<body>  

<h2>What will $("div > span") select?</h2>

<h4>This div element has two direct child elements, p and span:</h4>

<div style="border:1px solid black;padding:10px;">
  <p>This is a paragraph.</p>
  <span>This is a text inside a span.</span>
</div>

<h4>This div element has one direct child element, p:</h4>

<div style="border:1px solid black;padding:10px;">
  <p>This is a paragraph.  <span>This is a span element, inside the paragraph.</span></p> // <p> 내부에 있어서 해당안됨
</div>

=======================================================================

14. $("div p")	All <p> elements that are descendants of a <div> element
                                            ★ descendants : 후손들 ★

                                            <script>
$(document).ready(function(){
  $("div > span").css("background-color", "yellow");
});
</script>
</head>
<body>  

<h2>What will $("div > span") select?</h2>

<h4>This div element has two direct child elements, p and span:</h4>

<div style="border:1px solid black;padding:10px;">
  <p>This is a paragraph.</p>
  <span>This is a text inside a span.</span>
</div>

<h4>This div element has one direct child element, p:</h4>

<div style="border:1px solid black;padding:10px;">
  <p>This is a paragraph.  <span>This is a span element, inside the paragraph.</span></p> // <p> 내부에 있지만 해당됨
</div>

=======================================================================

15. $("div, p$) div요소와 p요소

=======================================================================​
<!DOCTYPE html>
<html>
<head>
    <title>웹 페이지</title>
    <script>
        // 화면 구성이 완료되면
        window.onload = function () {
            // h1 태그의 색상을 흰색으로 변경합니다.
            const header = document.querySelector('h1'); // 처음 나오는 요소만 선택함
            header.style.backgroundColor = 'red';
        };
    </script>
</head>
<body>
    <h1>Header 1</h1>
    <h1>Header 1</h1>
    <h1>Header 1</h1>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <title>DOM Basic</title>
    <!--  html 주석  -->
    <script>
        // 이벤트를 연결합니다.
        window.onload = function () {
            // 문서 객체를 선택합니다.
            const headers = document.querySelectorAll('h1'); 
            // 모든 h1 element(tag)를 선택하여 배열 객체 type으로 반환한다.
            // 따라서, index를 갖기때문에 headers 내의 값을 변경할 때 for를 사용했다.
            for (let i = 0; i < headers.length; i++) {
                // 변수를 선언합니다.
                const header = headers[i];
                // 문서 객체를 조작합니다.
                header.style.color = 'white';
                header.style.background = 'pink';
                header.innerHTML = 'Header에서 이 내용으로 바뀌었음.';
                // 객체명.innerHTML = '문자열' -> 기존의 메세지를 변경하여 넣는다.
            }
        };
    </script>
</head>
<body>
    <h1>Header</h1>
    <h1>Header</h1>
    <h1>Header</h1>
</body>
</html>

 

728x90