3 minutes quick understanding of jQuery

concept

As you can see from Baidu: jQuery is a fast and concise JavaScript framework, and is the first excellent JavaScript code library (or JavaScript framework) after Prototype

But let me just say, briefly: jQuery is designed to encapsulate the code that JavaScript uses most of the time. The essence of jQuery is to make it easier for me to write less code. Vue and React work the same way when you learn jQuery.


Access to elements

First we need to get the element via jQuery. Without it, you’ll have to bother with ElementSelector(), but when you’re using jQuery, we can just use $() :

$(document) // Select the entire document object

$('#myId') // Select the page element with ID myId

$('div.myClass') // Select the div element whose class is myClass

$('input[name=first]') // Select the input element whose name attribute is equal to first

$('div:visible') // Select the visible div element

$('div:gt(2)') // Select all div elements except the first three

Copy the code

The chain operation

The essence of jQuery is here. In native JS, we need to give variable objects and add many attributes to operate on an element with a multi-layer structure, whereas jQuery can operate in the form of a chain, which is very convenient:

$('div').find('h').eq(3).html('forever love');
Copy the code

The above code can be interpreted as:

$('div') // Find the div element

.find('h') // Select the h element

.eq(3) // Select the fourth h3 element (index starts at 0)

.html('forever love'); // Change its content to Forever Love
Copy the code

Add or delete check change

For any library, adding, deleting, checking, changing, and removing are basic operations

increase

To add a new element, simply place it in $()

$('<p>666</p>')
Copy the code
delete

There are two methods of deleting, which are.remove and.detach.

Delete the former is completely removed, the latter is still retained in memory for easy call

If you don’t want to delete the element but simply empty its contents, use.empty()

change

This step is often content specific

html(): // Read the contents of the tag body of the modified element
text(): // Read the plain text content of the tag body of the modified element
val(): // Read the value attribute of the modified element
Copy the code
move

There are two ways to move, so let’s say we want to move element A behind element B.

One is “self-acting”, which means moving the element you are manipulating directly:

$('a').insertAfter($('b'));
Copy the code

The other is “other-moving”, moving other elements:

$('b').after($('a'));
Copy the code

If you want to know more, I suggest you check out jQuery Design Ideas by Yifeng Ruan.