Home > Web Front-end > JS Tutorial > body text

How to set element attributes in javascript

青灯夜游
Release: 2023-01-05 16:11:37
Original
11484 people have browsed it

How to set element attributes in javascript: first use the "document.getElementById("id value")" statement to get the element object; then use "element object.setAttribute("attribute name", "attribute value")" statement to add or modify element properties.

How to set element attributes in javascript

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

How to set element attributes in javascript

In javascript, you can use the setAttribute() method to set element attributes

Syntax:

setAttribute("属性名称","属性值")
Copy after login

Example:

<img  id="img" src="img/1.jpg" / alt="How to set element attributes in javascript" >

<p id="demo">点击按钮来设置img图片的 width 属性。</p>

<button onclick="myFunction()">试一下</button>

<script>
	function myFunction() {
		document.getElementById("img").setAttribute("width", "200");
	}
</script>
Copy after login

Rendering:

How to set element attributes in javascript

##Extended information:

removeAttribute() is used To delete the tag attribute, syntax:

removeAttribute("属性名")
Copy after login

getAttribute() can get the value of the specified attribute of the tag, syntax:

getAttribute("属性名")
Copy after login
[Recommended learning:

javascript advanced tutorial]

The above is the detailed content of How to set 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