Latest web development tutorials

jQuery selector

jQuery Selector allows you to group HTML elements or a single element to operate.


jQuery selector

jQuery Selector allows you to group HTML elements or a single element to operate.

jQuery selector based on id elements, classes, types, attributes, attribute values, and so on "Find" (or select) HTML elements. It is based on existing CSS selectors , in addition, it also has some custom selectors.

All jQuery selectors start with a dollar sign: $ ().


Selectors

jQuery selectors select elements based on the element name.

Select all <p> elements in the page:

$("p")

Examples

User clicks the button, all <p> elements are hidden:

Examples

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

try it"


#id selector

jQuery #id selectors select elements specified by the id attribute of the HTML element.

id elements in the page should be unique, so you want to select only the elements in the page through #id selector.

Id by selecting the following syntax elements:

$("#test")

Examples

When the user clicks the button, the elements have id = "test" attribute will be hidden:

Examples

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

try it"


.class selector

jQuery class selector may find an element by the specified class.

The syntax is as follows:

$(".test")

Examples

User clicks the button after all elements with class = "test" are hidden attributes:

Examples

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

try it"


More examples

语法 描述 实例
$("*") 选取所有元素 在线实例
$(this) 选取当前 HTML 元素 在线实例
$("p.intro") 选取 class 为 intro 的 <p> 元素 在线实例
$("p:first") 选取第一个 <p> 元素 在线实例
$("ul li:first") 选取第一个 <ul> 元素的第一个 <li> 元素 在线实例
$("ul li:first-child") 选取每个 <ul> 元素的第一个 <li> 元素 在线实例
$("[href]") 选取带有 href 属性的元素 在线实例
$("a[target='_blank']") 选取所有 target 属性值等于 "_blank" 的 <a> 元素 在线实例
$("a[target!='_blank']") 选取所有 target 属性值不等于 "_blank" 的 <a> 元素 在线实例
$(":button") 选取所有 type="button" 的 <input> 元素 和 <button> 元素 在线实例
$("tr:even") 选取偶数位置的 <tr> 元素 在线实例
$("tr:odd") 选取奇数位置的 <tr> 元素 在线实例

Separate file using jQuery function

If your site contains many pages, and you want your jQuery function is easy to maintain, so please put your jQuery functions into separate .js file.

When we demonstrate in jQuery tutorial, the function will be added directly to the <head> section. However, put them in a separate file will be better, like this (file referenced by the src attribute):

Examples

<head>
<script src="http://cdn.static.w3big.com/libs/jquery/1.10.2/jquery.min.js">
</script>
<script src="my_jquery_functions.js"></script>
</head>