Home > Web Front-end > JS Tutorial > How to get the value of tag in js?

How to get the value of tag in js?

(*-*)浩
Release: 2020-09-19 11:31:36
Original
19969 people have browsed it

How to get the value of the tag in js: 1. js can use the innerText attribute of the object to get the value of the tag; 2. You can get the DOM element through JS first get the tag, and then use value, etc. to get the value of the tag That’s it.

How to get the value of tag in js?

#This article will introduce how to get the tag value in JS.

You can use the innerText property of the object to get the value of the label.

<style type="text/css">
.attr{border:1px solid red;width:40px;height:20px;margin:30px 40px;}
</style>
<div name="gary" age="30" class="attr" onclick="onBtn(this)">按钮</div>
<script type="text/javascript">
function onBtn(obj){
alert(obj.innerText);
};
</script>
Copy after login

You can also get DOM elements through JS (8 methods):

Get by ID (getElementById)

By name Attribute (getElementsByName)

By tag name (getElementsByTagName)

By class name (getElementsByClassName)

Get html method (document.documentElement)

Get Body method (document.body)

Get an element through the selector (querySelector)

Get a group of elements through the selector (querySelectorAll)

Get the label first, then Use value etc. to get the value of the label.

For example:

Use document.getElementsByTagName(‘tag name’);

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<script type="text/javascript">
    var div = document.getElementsByTagName('div')[0];
                //获取到了div 
                //element加了s表示是集合 获取的是一组元素 是伪数组
                //可以在获取元素后面加[写你想要的那个元素 数字表示 下标是0]; 
      alert(div.value);       
</script>
</body>
</html>
Copy after login

The above is the detailed content of How to get the value of tag in js?. For more information, please follow other related articles on the PHP Chinese website!

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