search
HomeWeb Front-endJS TutorialHow to manipulate DOM with jQuery

How to manipulate DOM with jQuery

Sep 27, 2017 am 09:53 AM
jqueryoperatemethod

1. jQuery operation style

2. jQuery operation attributes

3. jQuery animation simple operation

4. jQuery operation dom node addition and deletion operations

1. jq operation style

1.css operation:

Function: Setting Or modify the style and operate the style attribute

a. Set a single style, css (name/attribute name, value/attribute value);

$('#box').css(‘background’,'#000')

b. Set multiple styles, the parameter is the object css (obj);

$('#box').css({'background':'gray',
'width':'400px',
'height':'200px'
})

Get style:

.css(name)

Features, jQ’s css methods are all inline styles;

jqhidden When iterating through the formula, when a certain attribute of a collection is obtained, JQ will automatically print the 0th attribute.

When setting the operation, if there are multiple elements, then set the same value to all elements

box.eq(0).css('width',190);
box.eq(1).css('width',110);

..........

2.class operation

Function: processing style class

a.添加addClass(name);参数类名不用带点,并且不会覆盖之前的作用;
$("box").addClass("one");
b.移除removeClass("name");
$("box").removeClass("one");
c.判断hasClass是否有具体的类,返回值为布尔值
$("box").hasClass("one");//false
d.切换样式类toggleClass,需要切换的样式类名,如果有,移除该样式,如果没有,添加该样式。
$("box").toggleClass("one");切换样式类

2. jq operation attribute

1.attr operation

a.设置单个属性,attr(name,value);
$(“img”).attr(“title”,”哎哟,不错哦”);
b.设置多个属性(attr(obj));
$("img").attr({
title:"哎呦,不错哦“,
alt:"你很棒棒哟”,
style:"opacity:.5"
});
c.获取属性attr(name)
$(“img”).attr("title");

1. When obtaining attributes, only the attributes corresponding to the first element will be obtained, the same as the css method.

2. When getting an attribute, if the attribute does not exist, undefined will be returned.

d. Remove the attribute removeAttr(name);

Parameters: need to be removed If the attribute name is passed empty, no operation will be performed. Note that not all attributes are removed. Distinguish removeClass.

$("img").removeAttr("title");

2.prop operation Boolean attribute

For boolean form attributes such as checked, selected, and disabled, the attr method cannot be used. Only prop methods can be used.

Set attributes

$(“:checked”).prop(“checked”,true);

Add selected attributes to all selections, parameters (attribute name, true/false)

Get attributes

$(“:checked”).prop(“checked”);//返回true或者false;

三、jQuery basic animation

jquery provides three sets of basic animations. These animations are standard and regular effects. jquery also provides the function of custom animation.

1. Show and hide

show([speed],[callback]) and hide();

show() If no parameters are passed, display and hide directly

Parameters: speed: time (millisecond value), fixed string 'fast') = 200 nomal = 400 slow=600;

callback: callback function executed after the animation ends

hide()同show()方法一致

show/hide修改的是元素的width、height、opacity。

2.滑入与滑出

slideUp()与slideDown()

*如果不传参数,默认为nomal!(与show和hide区分 )

参数:时间,固定字符串

callback:执行动画结束后执行的回调函数

滑入滑出切换slideToggle(speed,callback)

$(selector).slideToggle(speed,callback);

//如果是隐藏状态,那么执行slideDown操作,如果是显示状态,那么执行slideUp操作。

3.淡入与淡出

fadeIn()与fadeOut()

用法与show好fadeOut一致

淡入淡出切换:

fadeToggle(speed,callback);

//如果当前元素处于隐藏状态,那么执行fadeIn操作,如果处于显示状态,那么执行fadeOut操作。

fade系列方法:修改的是元素的opacity

 4.基本动画小结

1. jQuery给我们提供了三组动画,show/hide、slideUp/slideDown、fadeIn/fadeOut

2. 动画切换方法:slideToggle、fadeToggle,toggle()。

3. show/slideDown/fadeIn三个是显示效果、hide/slideUp/fadeOut三个是隐藏效果。

4. show/hide修改的是元素的height,width,opacity。slide系列方法修改的是元素的height。fade系列方法修改的是元素的opacity。这三种方法修改的这些值,都是带数字的,因为带了数字才能做渐变。

5.自定义动画animate

animate:自定义动画

$(selector).animate({params},[speed],[callback]);

// {params}:要执行动画的CSS属性,带数字可以是对象(必写)

// speed:执行动画时长

时间和速度:毫秒数,字符串’swing‘两边慢,中间快/’linner‘匀速

// callback:动画执行完后立即执行的回调函数

例:

设置数值型的属性做动画

box.animate({

left:800;

width:800;

height:800 逐渐变大

transform:'rotate(360deg)'

},1000,'swing',function)

6.动画队列问题

在同一个元素上执行多个动画,那么对于这个动画来说,后面的动画会被放到动画队列中,等前面的动画执行完成了才会执行。

7.停止动画

stop()函数暂停当前执行动画

stop(clearQueue,jumpToEnd)

第一个参数:是否清楚队列,第二个参数:是否跳转最终效果,最后一帧

四、jQuery操作dom节点增删操作

1.创建元素

$(htmlStr)//html格式的字符串

$(“<span>这是一个span元素</span>”);

2.添加元素append/prepend

append方法:添加到当前的最后面。

参数:字符串(标签)或者jq对象

字符串:$(“p”).append(“这是一个span元素”);
JQ对象:var $span = $(“<span>这是一个span元素</span>”);
$(“p”).append($span);

prepend:追加到当前元素的最前面。

*如果添加的是已经存在的元素,那么会把之前的元素给干掉。(类似于剪切的功能)。

3.清空元素empty

empty:清空指定节点的所有元素,自身保留(清理门户)

1)$(“p”).empty();//清空p的所有内容(推荐使用,会清除子元素上绑定的内容,源码)
2)$(“p”).html(“”);//使用html方法来清空元素,不推荐使用,会造成内存泄漏,绑定的事件不会被清除。

4.删除元素remove

remove:相比于empty,自身也删除(自尽)

$(“p”).remove();

5.克隆元素clone

$(selector).clone();

复制$(selector)所匹配到的元素(深度复制)和原来的元素没有任何关系了。即修改新元素,不会影响到原来的元素。

The above is the detailed content of How to manipulate DOM with jQuery. For more information, please follow other related articles on the PHP Chinese website!

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
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft