900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > js DOM操作自定义属性

js DOM操作自定义属性

时间:2023-07-07 03:48:08

相关推荐

js DOM操作自定义属性

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

1. 获取元素的属性值

element.属性名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. 设置元素的属性值

element.属性名 = “值”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>

移除前:

移除后:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。