- JavaScript:Moving to ES2015
- Ved Antani Simon Timms Narayan Prusty
- 311字
- 2021-07-09 19:07:42
Traversal and manipulation
We discussed various methods of element selection using jQuery. We will discuss several DOM traversal and manipulation methods using jQuery in this section. These tasks would be rather tedious to achieve using native DOM manipulation. jQuery makes them intuitive and elegant.
Before we delve into these methods, let's familiarize ourselves with a bit of HTML terminology that we will be using from now on. Consider the following HTML:
<ul> <-This is the parent of both 'li' and ancestor of everything in <li> <-The first (li) is a child of the (ul) <span> <-this is the descendent of the 'ul' <i>Hello</i> </span> </li> <li>World</li> <-both 'li' are siblings </ul>
Using jQuery traversal methods, we select the first element and traverse through the DOM in relation to this element. As we traverse the DOM, we alter the original selection and we are either replacing the original selection with the new one or we are modifying the original selection.
For example, you can filter an existing selection to include only elements that match a certain criterion. Consider this example:
var list = $( 'li' ); //select all list elements // filter items that has a class 'highlight' associated var highlighted = list.filter( '.highlight ); // filter items that doesn't have class 'highlight' associated var not_highlighted = list.not( '.highlight );
jQuery allows you to add and remove classes to elements. If you want to toggle class values for elements, you can use the toggleClass()
method:
$( '#usename' ).addClass( 'hidden' ); $( '#usename' ).removeClass( 'hidden' ); $( '#usename' ).toggleClass( 'hidden' );
Most often, you may want to alter the value of elements. You can use the val()
method to alter the form of element values. For example, the following line alters the value of all the text
type inputs in the form:
$( 'input[type="text"]' ).val( 'Enter usename:' );
To modify element attributes, you can use the attr()
method as follows:
$('a').attr( 'title', 'Click' );
jQuery has an incredible depth of functionality when it comes to DOM manipulation—the scope of this module restricts a detailed discussion of all the possibilities.
- Expert C++
- Mastering OpenCV Android Application Programming
- 算法基礎(chǔ):打開程序設(shè)計之門
- Lua程序設(shè)計(第4版)
- Kinect for Windows SDK Programming Guide
- EPLAN實戰(zhàn)設(shè)計
- Java高并發(fā)核心編程(卷1):NIO、Netty、Redis、ZooKeeper
- 一本書講透Java線程:原理與實踐
- MySQL入門很輕松(微課超值版)
- uni-app跨平臺開發(fā)與應(yīng)用從入門到實踐
- C指針原理揭秘:基于底層實現(xiàn)機制
- 物聯(lián)網(wǎng)系統(tǒng)架構(gòu)設(shè)計與邊緣計算(原書第2版)
- 大數(shù)據(jù)時代的企業(yè)升級之道(全3冊)
- JavaScript前端開發(fā)基礎(chǔ)教程
- Java從入門到精通(視頻實戰(zhàn)版)