Home  >  Article  >  Web Front-end  >  How to get the background color through id in html

How to get the background color through id in html

青灯夜游
青灯夜游Original
2021-06-21 14:57:032090browse

Method to obtain the background color through id: First use the "document.getElementById('id value')" statement to obtain the specified element object; then use "element object.style.background" to return the background color value.

How to get the background color through id in html

The operating environment of this tutorial: Windows 7 system, HTML5 version, Dell G3 computer.

htmlGet the background color through id

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<script>
function displayResult(){
	var s=document.getElementById(&#39;h1&#39;).style.background;
	document.getElementById(&#39;div&#39;).innerHTML="h1标签的背景色为"+s;
}
</script>
</head>
<body>

<h1 id="h1" style="background: red;">Hello World!</h1>
<div id="div"></div>
<br>
<button type="button" onclick="displayResult()">获取背景色</button>

</body>
</html>

Rendering:

How to get the background color through id in html

Description:

## The #getElementById() method returns a reference to the first object with the specified ID.

  • If there is no element with the specified ID, return null

  • If there are multiple elements with the specified ID, return the first one.

The background property sets or returns up to five independent background properties in shorthand form.

With this property, you can set/return:

  • background-color

  • background-image

  • background-repeat

  • background-attachment

  • background-position

Syntax

Set the background attribute:

Object.style.background="color image repeat attachment position"

Return the background attribute:

Object.style.background

For more programming-related knowledge, please visit:

Introduction to Programming! !

The above is the detailed content of How to get the background color through id in html. 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