Home  >  Article  >  Web Front-end  >  How to modify the style attribute of an element in javascript

How to modify the style attribute of an element in javascript

青灯夜游
青灯夜游Original
2022-01-26 16:30:5621924browse

In JavaScript, you can use the setAttribute() method to modify the style attribute. This method can modify the attribute value for an existing specified attribute. The syntax is "element object.setAttribute("style","style code" );".

How to modify the style attribute of an element in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

In javascript, you can use the setAttribute() method to modify the style attribute.

The setAttribute() method adds the specified attribute and assigns it the specified value. If this specified property already exists, the value is only set/changed.

Syntax:

element.setAttribute(attributename,attributevalue)
Parameters Type Description
attributename String Required. The name of the attribute you wish to add.
attributevalue String Required. The attribute value you wish to add.

Example:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
	</head>
	<body>
		<div id="box" style="background-color: black;color: white;border: 2px solid red;">一个div元素</div><br />
		<button onclick="replaceMessage()"> 修改style属性的值</a>

			<script type="text/javascript">
				function replaceMessage() {
					var div = document.getElementById("box"); 
					div.setAttribute("style","background-color: #FFC0CB;color: black;border: 3px dashed peru;");
				}
			</script>

	</body>
</html>

How to modify the style attribute of an element in javascript

[Related recommendations: javascript learning tutorial]

The above is the detailed content of How to modify the style attribute of an element in javascript. 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