1. Use jQuery to get the content or attributes of DOM elements
A very important part of jQuery is the ability to manipulate the DOM.
jQuery provides a series of DOM-related methods, which makes it easy to access and manipulate elements and attributes.
Before that, let me talk about what DOM is
JUDGMENT
The full name of DOM is Document Object Model. To put it bluntly, it is our tag, like the <p> tag, this is a DOM node
Then let's take a look at how to get the content or attributes of DOM elements
1. Get content
There are three ways to get content
- text()-Set or return the text content of the selected element
- html()-Set or return the content of the selected element (including HTML markup)
- val()-Set or return the value of a form field
Let's take a look at how to use
text()
We click the button
As you can see, we have obtained all the content in the p tag, including the strong tag
html()
It’s the same example just now, we only need to modify the text to html, let’s take a look at the effect
As you can see, we not only get the content, but also the tags
val()
val is actually used to get the value of the DOM node, let’s look at it again
Let's run it
As you can see, there is no problem
2. Get properties
Let's take a look at how to get attributes. To get the attribute, we need to use the attr method, and then we need to pass in a parameter, for example, if we want to get an id, then we pass an id, if we get a value, then we pass a value, let’s take a look
Run it
Let's get another type
Also ok
2. Use jQuery to set the content or attributes of DOM elements
In fact, this setting value is very similar to the obtained value, I hope you can draw inferences about it.
1. Set the value of the DOM element content
text()
We click the button
html()
The difference between html and text, html can set some tag values, let’s take a look
Then we click the button
Is OK, just replace it with button
val()
This is the same, it is to set the value of the tag with the value attribute such as input, let's take a look
Click button
OK
2. Set attributes to DOM element content
Properties are also very easy, let’s take a look
Let's click on the button to see if we can use the style of a
Ok, no problem
Three, use jQuery to modify the css style
We can modify the style of css through jQuery, let's take a look at an example
Then we click on the button to see the effect
OK, but if we want to make this yellow background, but also enlarge the text, how do we do this? Of course, jQuery has already thought about it for us, let’s take a look
We only need to define it as a json string, let’s click and try
There is no problem