자바스크립트_JQuery

JQuery Selector (html 객체 선택 방법)

긋대디 2019. 1. 4. 20:49

jQuery Selectors


jQuery의 Selector는 HTML 요소 (들)을 선택하고 조작 할 수 있습니다.

jQuery의 Selector는 이름, ID, 클래스, 유형, 속성 값을 기반으로 HTML 요소를 "찾기"(또는 선택)하는 데 사용됩니다. 또한, 기존의  CSS 셀렉터 기반으로 하는 일부 사용자 정의 셀렉터가 있습니다.

jQuery를 모든 선택기는 달러 기호와 괄호로 시작 : $를 ().



jQuery의 모든 선택자는 달러 기호와 괄호로 시작합니다 : $ ().

다음과 같이 페이지의 모든 <p> 요소를 선택할 수 있습니다. :

$("p")

Example

사용자가 버튼을 클릭하면, 모든 <p>요소는 표시되지 않습니다 :

Example

$(document).ready(function(){
  $("button").click(function(){
    $("p").hide();
  });
});


The #id Selector


jQuery #id selector는 HTML 태그의 id 속성을 사용하여 특정 요소를 찾습니다. id는 페이지 내에서 고유해야하므로 단일 고유 요소를 찾으려면 #id selector를 사용해야합니다. 특정 ID가있는 요소를 찾으려면 HTML 요소의 ID 뒤에 해시 문자를 씁니다.

$("#test")

Example

사용자가 버튼을 클릭하면 id = "test"인 요소가 숨겨집니다.:

Example

$(document).ready(function(){
  $("button").click(function(){
    $("#test").hide();
  });
});


The .class Selector


jQuery 클래스 선택기는 특정 클래스가있는 요소를 찾습니다. 특정 클래스가있는 요소를 찾으려면 마침표를 쓰고 클래스 이름을 입력하십시오.:

$(".test")

Example

사용자가 버튼을 클릭하면 class = "test"인 요소가 숨겨집니다.:

Example

$(document).ready(function(){
  $("button").click(function(){
    $(".test").hide();
  });
});




More Examples of jQuery Selectors

SyntaxDescriptionExample
$("*")Selects all elementsTry it
$(this)Selects the current HTML elementTry it
$("p.intro")Selects all <p> elements with class="intro"Try it
$("p:first")Selects the first <p> elementTry it
$("ul li:first")Selects the first <li> element of the first <ul>Try it
$("ul li:first-child")Selects the first <li> element of every <ul>Try it
$("[href]")Selects all elements with an href attributeTry it
$("a[target='_blank']")Selects all <a> elements with a target attribute value equal to "_blank"Try it
$("a[target!='_blank']")Selects all <a> elements with a target attribute value NOT equal to "_blank"Try it
$(":button")Selects all <button> elements and <input> elements of type="button"Try it
$("tr:even")Selects all even <tr> elementsTry it
$("tr:odd")Selects all odd <tr> elementsTry it

Use our jQuery Selector Tester to demonstrate the different selectors.

For a complete reference of all the jQuery selectors, please go to our jQuery Selectors Reference.


Functions In a Separate File

If your website contains a lot of pages, and you want your jQuery functions to be easy to maintain, you can put your jQuery functions in a separate .js file.

When we demonstrate jQuery in this tutorial, the functions are added directly into the <head> section. However, sometimes it is preferable to place them in a separate file, like this (use the src attribute to refer to the .js file):

Example

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="my_jquery_functions.js"></script>
</head>


jQuery Exercises

Test Yourself With Exercises

Exercise:

Use the correct selector to hide all <p> elements.

$("").hide();

Start the Exercise