Home >Web Front-end >JS Tutorial >How to set element width in javascript

How to set element width in javascript

青灯夜游
青灯夜游Original
2021-04-27 17:16:2311234browse

Javascript method to set the width of an element: first use the "document.getElementById("id value")" statement to obtain the element object; then use the "element object.style.width="width value"" statement to set the element width.

How to set element width in javascript

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

javascript sets element width

Principle:

  • Get element object

  • The width attribute of the HTML DOM Style object sets the width of the element.

Code example:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<style>
			img {
				width: 200px;
			}
		</style>
	</head>

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

<p id="demo">img图片宽度为200px。</p>

<button onclick="myFunction()">设置img图片的宽度</button>

<script>
	function myFunction() {
		document.getElementById("img").style.width="300px";
		document.getElementById("demo").innerHTML="img图片宽度为300px。";
	}
</script>
	</body>

</html>

Rendering:

How to set element width in javascript

Description:

The width property of the Style object can set the width of the element.

Syntax:

Object.style.width=auto|length|%
Value Description
auto default. The browser can calculate the actual width.
% Defines the width based on the percentage of its containing block.
length Use px, cm and other units to define the width.

Method to find elements:

1. Get elements based on id

document.getElementById("id属性的值");

2. Based on tag name Get the element

document.getElementsByTagName("标签的名字");

3. Get the element based on the value of the name attribute

document.getElementsByName("name属性的值");

4. Get the element based on the class attribute

document.getElementsByClassName("类样式的名字");

5. Get the element based on the css path (get one)

document.querySelector("css路径");

6. Get elements based on css path (get a group)

document.querySelectorAll("css路径");

[Recommended learning: javascript advanced tutorial]

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