Home  >  Article  >  Web Front-end  >  jquery adds style to div

jquery adds style to div

王林
王林Original
2023-05-28 16:04:37930browse

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>

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>

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

var myDiv = $("#myDiv");

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

myDiv.addClass("my-class");

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;
}

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");

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!

Statement:
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