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');
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');
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');
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');
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!