Home  >  Article  >  Web Front-end  >  jquery sets div background to red

jquery sets div background to red

WBOY
WBOYOriginal
2023-05-18 14:46:371014browse

How to use jQuery to set the background of a div to red

In web development, setting the style of elements is a very common operation, and one of the most common styles is the background color. In this article, we will introduce how to use jQuery to set the background of div elements in HTML pages to red.

jQuery is a popular JavaScript library used to simplify access and manipulation of DOM elements and their attributes between HTML documents. To use jQuery, you need to introduce the jQuery library in your HTML page. In this article, we assume that you have introduced the jQuery library in your HTML page.

  1. HTML file preparation

First, we need to define a div element in HTML.

<div id="myDiv">hello world</div>

We use the unique identifier with the id "myDiv" to refer to the element of this div.

  1. Set div background using jQuery

In order to set the background color of a div element, we can use jQuery's .css() method, which allows us to set the CSS of the element Attributes. We can use the following code to set the background color of a div:

$(document).ready(function(){
  $('#myDiv').css('background-color', 'red');
});

This code uses jQuery to select the div element in the page and uses the .css() method to set its background color to red. Please note that we passed two parameters in the .css() method. The first parameter is the name of the CSS property to be set, and the second parameter is the value of the property.

  1. Other properties

In addition to the background color, we can also use the .css() method to set other CSS properties. For example, we can change properties like div width and height.

$(document).ready(function(){
  $('#myDiv').css({
    'background-color': 'red',
    'width': '200px',
    'height': '200px'
  });
});

The above code demonstrates how to set multiple values ​​​​of CSS properties using a JavaScript object that contains a list of property/value pairs. Separate each attribute/value pair with a comma.

Summary

In this article, we introduced how to use jQuery to set the background color of a div element in an HTML page to red. We used jQuery's .css() method and passed the result the CSS property we wanted to change and its value.

The above is the detailed content of jquery sets div background to red. 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