自定义属性:在日常开发中,html的内置属性已经无法满足程序员的日常开发,所以需要我们自己定义属性,H5给我们新增了自定义属性,为了防止自定义属性和内置属性引起歧义,所以H5规定自定义属性以data-开头定义。

1. 获取元素的属性值

  1. element.属性名
  2. element.getAttribute(“属性名”)
element.属性名 和 element.getAttribute(“属性名”) 的区别:

element.属性名:获取的是内置属性(元素本身自带的属性),不能获取自定义属性;
element.getAttribute(“属性名”):主要获取我们自定义属性,当然也可以获取内置属性。

<body>
	<input type="text" value="你好" data-index="0" />
</body>

<script>
	const input = document.querySelector("input");
	
	console.log(input.value); // "你好"

	console.log(input.getAttribute("value")); // "你好"
	console.log(input.getAttribute("data-index")); // "0"
</script>

2. 设置元素的属性值

  1. element.属性名 = “值”
  2. element.setAttribute(“属性名”,“值”)
element.属性名 = “值” 和 element.setAttribute(“属性名”,“值”) 的区别:

element.属性名 = “值”: 主要用来设置内置属性;
element.setAttribute(“属性名”,“值”):主要用来设置/添加自定义属性,也可以设置内置属性;

<body>
	<input type="text" value="你好" data-index="0" />
</body>

<script>
	const input = document.querySelector("input");
	
	input.value= "hello";
	console.log(input.value); // "hello"

	input.setAttribute("value", "hi");
    console.log(input.getAttribute("value")); // "hi"

    input.setAttribute("data-index", "1");
    console.log(input.getAttribute("data-index")); // "1"

    input.setAttribute("data-name", "shy");
    console.log(input.getAttribute("data-name")); // "shy"
</script>

在这里插入图片描述

3. 移除属性

element.removeAttribute(“属性名”):可以移除内置属性,也可以移除自定义属性。

<body>
	<input type="text" value="你好" data-index="0" />
</body>

<script>
	const input = document.querySelector("input");
	
	input.removeAttribute("value");
	input.removeAttribute("data-index");
</script>

移除前:
在这里插入图片描述
移除后:
在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐