Home > Web Front-end > JS Tutorial > How to change element attributes in JavaScript

How to change element attributes in JavaScript

青灯夜游
Release: 2021-11-08 11:29:58
Original
2148 people have browsed it

How to change element attributes in JavaScript: 1. Use the "element object.attribute = new value" statement; 2. Use the "element object.setAttribute('attribute','attribute value')" statement.

How to change element attributes in JavaScript

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

JavaScript to change element attributes

1. Use the "element object.attribute = new value" statement

Example: Modified the value of the src attribute of the element:

<img id="myImage" src="smiley.gif">

<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>
Copy after login

Method 2: Use the setAttribute() function

## 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 object.setAttribute('attribute','attribute value');

<div>hello</div> 
<div id="box">欢迎来到PHP中文网!</div> 
<script type="text/javascript">
	var box=document.getElementById("box");
	box.setAttribute(&#39;style&#39;,&#39;color:red;border:1px solid #008000&#39;);
	// 给box元素设置的是行内样式
</script>
Copy after login
[Recommended learning:

javascript advanced tutorial]

The above is the detailed content of How to change element attributes in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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