Home > Web Front-end > JS Tutorial > Introduction to the use of JQuery selector_jquery

Introduction to the use of JQuery selector_jquery

WBOY
Release: 2016-05-16 17:36:20
Original
1283 people have browsed it

jQuery element selectors and attribute selectors allow you to select HTML elements by tag name, attribute name, or content.

jQuery Element Selectors: jQuery uses CSS selectors to select HTML elements.

$("p") selects the

element.

$("p.intro") selects all

elements with class="intro".

$("p#demo") selects the first

element with id="demo".

jQuery Attribute Selector : jQuery uses an XPath expression to select elements with a given attribute.

$("[href]") selects all elements with href attribute.

$("[href='#']") selects all elements with an href value equal to "#".

$("[href!='#']") selects all elements with href value not equal to "#".

$("[href$='.jpg']") selects all elements whose href value ends with ".jpg".

Selector instance

语法 描述
$(this) 当前 HTML 元素
$("p") 所有

元素

$("p.intro") 所有 class="intro" 的

元素

$(".intro") 所有 class="intro" 的元素
$("#intro") id="intro" 的第一个元素
$("ul li:first") 每个
    的第一个
  • 元素
$("[href$='.jpg']") 所有带有以 ".jpg" 结尾的属性值的 href 属性
$("div#intro .head") id="intro" 的
元素中的所有 class="head" 的元素

Get/set content - text(), html() and val()

We will use the same three methods from the previous chapter to set up the content:

  • text() - Sets or returns the text content of the selected element
  • html() - Sets or returns the content of the selected element (including HTML markup)
  • val() - Set or return the value of a form field
  • attr() - Sets and returns the attribute value of the selected element

The four jQuery methods above: text(), html(), val() and attr() also have callback functions. The callback function takes two parameters: the index of the current element in the selected element list, and the original (old) value. Then return the string you wish to use as the function's new value.

$("#btn1").click(function(){
 $("#test1").text(function(i,origText){
 return "Old text: " + origText + " New text: Hello world ! (index: " + i + ")"; //return newText;
 });
});
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template