jquery adds style to div

王林
Release: 2023-05-28 16:04:37
Original
977 people have browsed it

jQuery is a widely used Javascript library that provides many convenient tools and methods for web developers. One of them is that it provides an easy way to add styles to HTML elements, such as DIV elements. This article will show you how to use jQuery to add styles to DIV.

Before using jQuery, please make sure you have introduced the jQuery library file in your HTML. You can introduce it in the following ways:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Copy after login

Once you have introduced the jQuery library file, you can use the methods it provides.

First, we need a DIV element to add styles. In this example, we will use the following HTML code:

<div id="myDiv">This is my div element</div>
Copy after login

Next, we need to use JavaScript code to get a reference to this DIV element, which can be done by:

var myDiv = $("#myDiv");
Copy after login

Continue Next, we can use the addClass() method to add a CSS class, as follows:

myDiv.addClass("my-class");
Copy after login

The my-class class defined in the CSS file will be applied to the myDiv element, for example:

.my-class {
    background-color: yellow;
    font-size: 18px;
    padding: 10px;
}
Copy after login

Now, when we run this code, the DIV element's background color will change to yellow, the font size will be 18 pixels, and it will have 10 pixels of padding.

If we want to change the style of this DIV element, we can use the css() method, as follows:

myDiv.css("background-color", "red");
Copy after login

This will make the background color red.

Now, we have mastered the basic method of how to use jQuery to add styles to DIV elements. Of course, jQuery also provides many other useful methods and properties that allow us to better control the style and behavior of HTML elements. Hope this article helps you!

The above is the detailed content of jquery adds style to div. 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