Home > Web Front-end > Front-end Q&A > How to set all elements under div in jquery

How to set all elements under div in jquery

PHPz
Release: 2023-04-17 10:33:39
Original
641 people have browsed it

Recently, I encountered a problem when developing a website: How to use jQuery to set all elements under a certain div?

On my website I have a div that contains several p, h2 and a tags. I want to set the color of p to red and the color of h2 and a to blue using jQuery.

To achieve this, I first need to select this div, then use jQuery selectors to select all elements within it and set their color to the corresponding value.

First, I use jQuery's $() function to select this div, as shown below:

var myDiv = $('div');
Copy after login

Next, I use jQuery's find() function to select all p, h2, and a tags and set their colors to red and blue:

myDiv.find('p').css('color', 'red');
myDiv.find('h2, a').css('color', 'blue');
Copy after login

Here, I use jQuery's css() function to set the color of the elements.

If you don't want to use multiple css() functions, you can merge all elements together, as shown below:

myDiv.find('p, h2, a').css('color', 'red');
Copy after login

In this way, all elements will be selected together, and Set their color.

On my website I have another div that I want to set its background color to yellow. To achieve this, I can use the following code:

$('div#myOtherDiv').css('background-color', 'yellow');
Copy after login

Here, I use jQuery's $() function to select the div with the ID myOtherDiv. I then set its background color to yellow using the css() function.

In short, it is very easy to set all elements under a div using jQuery. First, select this div, then use the find() function to select all elements within it and set their properties to the appropriate values. If you want to select multiple elements and merge them together, you can separate them with commas.

I hope this article can be helpful to you, thank you for reading!

The above is the detailed content of How to set all elements under div in jquery. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template