LEARNING JAVASCRIPT - Trang 302

$

(

'p'

).

html

(

'<i>ALL</i> PARAGRAPHS REPLACED'

);

This brings us to an important point about jQuery: jQuery makes it very easy to

operate on many elements at once. With the DOM API,

document.querySelector

All()

will return multiple elements, but it’s up to us to iterate through them and per‐

form whatever operations we want to. jQuery handles all the iteration for you, and by

default assumes that you want to perform actions on every element in the jQuery

object. What if you only want to modify the third paragraph? jQuery provides a

method

eq

that returns a new jQuery object containing a single element:

$

(

'p'

)

// matches all paragraphs

.

eq

(

2

)

// third paragraph (zero-based indices)

.

html

(

'<i>THIRD</i> PARAGRAPH REPLACED'

);

To remove elements, simply call

remove

on a jQuery object. To remove all

paragraphs:

$

(

'p'

).

remove

();

This demonstrates another important paradigm in jQuery development: chaining. All

jQuery methods return a jQuery object, which allows you to chain calls as we just did.

Chaining allows for very powerful and compact manipulation of multiple elements.
jQuery provides many methods for adding new content. One of these methods is

append

, which simply appends the provided content to every element in the jQuery

object. For example, if we wanted to add a footnote to every paragraph, we can do so

very easily:

$

(

'p'

)

.

append

(

'<sup>*</sup>'

);

append

adds a child to the matched elements; we can also insert siblings with

before

or

after

. Here is an example that adds

<hr>

elements before and after every para‐

graph:

$

(

'p'

)

.

after

(

'<hr>'

)

.

before

(

'<hr>'

);

These insertion methods also include counterparts

appendTo

,

insertBefore

, and

insertAfter

that reverse the order of the insertion, which can be helpful in certain

situations. For example:

$

(

'<sup>*</sup>'

).

appendTo

(

'p'

);

// equivalent to $('p').append('<sup>*</sup>')

$

(

'<hr>'

).

insertBefore

(

'p'

);

// equivalent to $('p').before('<hr>')

$

(

'<hr>'

).

insertAfter

(

'p'

);

// equivalent to $('p').after('<hr>');

jQuery also makes it very easy to modify the styling of an element. You can add

classes with

addClass

, remove classes with

removeClass

, or toggle classes with

toggleClass

(which will add the class if the element doesn’t have it, and remove the

278 | Chapter 19: jQuery

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.