search
HomeWeb Front-endJS TutorialjQuery basic tutorial for operating various elements_jquery

The examples in this article describe jQuery's operations on elements, including basic operations, selecting elements to be operated on, and processing DOM elements. It has a good reference value for learning jQuery. Share it with everyone for your reference. The specific analysis is as follows:

1. Basics

jquery object set:

$(): collection of jquery objects

Get elements in jquery object set:

Get the javascript element in the wrapper using index:

var temp = $('img[alt]')[0]

Use jquery's get method to get the javascript elements in the jquery object set:

var temp = $('img[alt]').get(0)

Use jquery's eq method to get the jquery object elements in the jquery object set:

$('img[alt]').eq(0)
$('img[alt]').first()
$('img[alt]').last()

Convert jquery object set to javascript array:

var arr = $('label+button').toArray()

All button elements of the same level behind the label are converted into javascript arrays

Index of jquery object set:
var n = $('img').index($('img#id')[0]) Note: The index() parameter is a javascript element
var n = $('img').index('img#id') is equivalent to the previous line. If not found, returns -1
var n = $('img').index() gets the index of img in the same level element

Add more jquery object sets to the jquery object set:
Use commas:

$('img[alt],img[title]')

Use add method:

$('img[alt]').add('img[title]')

Take different methods for different jquery objects:

$('img[alt]').addClass('thickBorder').add('img[title]').addClass('');

Add newly created element to jquery object set:

$('p').add('<div></div>');

Delete elements from jquery object set:

$('img[title]').not('[title*=pu]')
$('img').not(function(){return !$(this).hasClass('someClassname')})

Filter jquery object set:
$('td').filter(function(){return this.innerHTML.match(^d $)}) filters td

containing numbers

Get a subset of jquery object set

$('*').slice(0,4) A new set of jquery objects containing the first 4 elements
$('*').slice(4) A new set of jquery objects containing the first 4 elements
$('div').has('img[alt]')

Convert elements in jquery object set:

var allIds = $('div').map(function(){
 return (this.id==undefined) &#63; null : this.id;
}).get();

The above example can be converted into a javascript array through the get method.

Traverse the elements in the jquery object set:

$('img').each(function(n){
 this.alt = '这是第['+n+']张图片,图片的id是' + this.id;
})
$([1,2,3]).each(function(){alert(this);})

Get a set of jquery objects using relationships between elements:

$(this).closest('div') For example, in which div the triggered button occurs
$(this).siblings('button[title="Close"]')All sibling elements, excluding itself
$(this).children('.someclassname')All child node elements, excluding duplicate child nodes
$(this).closest('') is close to the ancestor element
$(this).contents() is a set of jquery objects composed of element contents. For example, you can get the

Other ways to get jquery object sets:

$(this).find(p span)

Determine whether it is a jquery object set:

var hasImg = $('*').is('img');

jquery method:

$().hide()
$().addClass('')
$().html('')
$('a').size()Number of elements

jquery selector:

$('p:even')
$('tr:nth-child(1)')
$('body > div') direct child element
$('a[href=$='pdf']')Select according to attributes
$(div:has(a)) filter

jquery function:

$.trim()
jquery execution time:
$(document).ready(function(){});
$(function(){});

Create DOM element:

$('<p></p>').insertAfter();
$('<img  alt="jQuery basic tutorial for operating various elements_jquery" >',{
 src: '',
 alt: '',
 title: '',
 click: function(){}
}).css({
 cursor:'pointer',
 border:'',
 padding:'',
 backgroundColor:'white'
}).append('');

jquery extension:

$.fn.disable = function(){
 return this.each(function(){
 if(this.disabled != null) this.disabled = true;
 })
};
$('').disable();

jquery测试元素是否存在:

if(item)(){}else{} 宽松测试
if(item != null) 推荐测试,能把null和undefined区别开

2、选择要操作的元素

根据标签名:$('a')  
根据id:$('#id')
根据类名:$('.someclassname')
满足多个条件:$('a#id.someclassname') 或 $('div,span')
某个元素的所有子节点:$(p a.someclassname)
某个元素的直接子节点:$(ul.myList > li)
根据属性名:
$(a[href^='http://']) 以...开头
$(href$='.pdf')以...结尾
$(form[method])包含method属性的form
$(intput[type='text'])
$(intput[name!=''])
$(href*='some')包含

某元素后的第一个元素:$(E+F)匹配的是F,F是E后面的第一个元素

某元素后的某一个元素:$(E~F)匹配的是F,F是E后面的某一个元素

通过位置:

$(li:first)第一个li
$(li:last)最后一个li
$(li:even)偶数行li
$(li:odd)奇数行li
$(li:eq(n))第n个元素,索引从0开始
$(li:gt(n))第n个元素之后的元素,索引从0开始
$(li:lt(n))第n个元素之前的元素,索引从0开始
$(ul:first-child)列表中的第一个li
$(ul:last-child)列表中的最后一个li
$(ul:nth-child(n))列表中的第n个li
$(ul:only-child)没有兄弟li的ul
$(ul:nth-child(even))列表中的偶数行li,odd为计数行li
$(ul:nth-child(5n+1))列表中被5除余1的li

通过过滤器:

$(input:not(:checkbox))
$(':not(img[src*="dog"])')
$('img:not([src*="dog"])')
$(div:has(span))
$('tr:has(img[src$="pu.png"])')
$(tr:animated)处于动画状态的tr
$(input:button)包括type类型为button,reset,submit的Input
$(input:checkbox)等同于$(input[type=checkbox])
$(span:contains(food))包含文字food的span
$(input:disabled)禁用
$(input:enabled)启用
$(input:file)等同于$(input[type=file])
$(:header)h1到h6
$(input:hidden)
$(input:image)等同于$(input[type=image])
$(:input)包括input, select, textarea, button元素
$(tr:parent)
$(input:password)等同于$(input[type=password])
$(input:radio)等同于$(input[type=radio])
$(input:reset)等同于$(input[type=reset])或$(button[type=reset])
$('.clssname:selected')
$(input:submit)等同于$(input[type=submit])或$(button[type=submit])
$(input:text)等同于$(input[type=text])
$(div:visible)

3、处理DOM元素  

操作元素的属性:

$('*').each(function(n){
 this.id = this.tagName + n;
})

获取属性值:

$('').attr('');

设置属性值:

$('*').attr('title', function(index, previousValue){
 return previousValue + ' I am element ' + index + ' and my name is ' + this.id;
}) //为一个属性设置值
$('input').attr({
 value: '',
 title: ''
}); //为多个属性设置值

删除属性:

$('p').removeAttr('value');

让所有链接都在新窗口中打开:

$('a[href^="http://"]').attr('target',"_blank");

避免表单多次提交:

$("form").submit(function(){
 $(":submit", this).attr("disabled","disabled");
})

添加类名:

$('#id').addClass('')

删除类名:

$('#id').removeClass('')

切换类名:

$('#id').toggleClass('')

存在就删除类名,不存在就添加类名
判断是否含有类名:

$('p:first').hasClass('') $('p:first').is('')

以数组形式返回类名列表:

$.fn.getClassNames = function(){
 var name = this.attr('someclsssname');
 if(name != null){
 return name.split(" ");
 }
 else
 {
 return [];
 }
}

设置样式:

$('div.someclassname').css(function(index, currentWidth){
 return currentWidth + 20;
});
$('div').css({
 cursor: 'pointer',
 border: '1px solid black',
 padding: '12px 12px 20px 20x',
 bacgroundColor: 'White'
});

有关尺寸:

$(div).width(500)
$('div').height()
$('div').innerHeight()
$('div').innerWidth()
$('div').outerHeight(true)
$('div').outerWidth(false)

有关定位:

$('p').offset()相对于文档的参照位置
$('p').position()偏移父元素的相对位置
$('p').scrollLeft()水平滚动条的偏移值
$('p').scrollLeft(value)
$('p').scrollTop()
$('p').scrollTop(value)

有关元素内容:

$('p').html()
$('p').html('')
$('p').text()
$('p').text('')

追加内容

在元素末尾追加一段html:

$('p').append('<b>some text</b>');

在元素末尾dom中现有的元素:

$('p').append($(a.someclassname))

在元素开头追加:

$("p").prepend()

在元素的前面追加:

$("span").before()

在元素的后面追加:

$("span")after()

把内容追加到末尾:

appendTo(targets)

把内容追加到开头:

prependTo(targets)

把内容追加到元素前面:

insertBefore(targets)

把内容追加到元素后面:

$('<p></p>').insertAfter('p img');

包裹元素:

$('a.someclassname').wrap("

")
$('a.someclassname').wrap($("div:first")[0])
$('a.someclassname').wrapAll()
$('a.someclassname').wrapInner()
$('a.someclassname').unWrap()

删除元素:

$('.classname').remove()删除元素,绑定到元素上的事件和数据也会被删除
$('.classname').detach()删除元素,但保留事件和数据
$('.classname').empty()不删除元素,但清空元素内容

复制元素:

$('img').clone().appendTo('p.someclassname')
$('ul').clone().insertBefore('#id')

替换元素:

$('img[alt]').each(function(){
 $(this).replaceWith('<span>' + $(this).attr('alt') + '</span>');
})
$("p").replaceAll("<b></b>")

关于表单元素的值:

$('[name="radioGroup"]:checked').val()获取单选按钮的值,如果没有选中一个,返回undefined
var checkboxValues = $('[name="checkboxGroup"]:checked').map(function(){
 return $(this).val();
}).toArray(); //获取多选框的值

对于

相信本文所述对大家的jQuery程序设计有一定的借鉴价值。

Statement
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
JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)