JS(原生js和jq方式)获取元素属性(自定义属性),删除属性(自定义属性)
JS(原生js和jq方式)获取元素属性(自定义属性),删除属性(自定义属性)
以下内容:
一、获取元素的属性
二、设置元素的属性
三、删除元素的属性
一、获取元素的属性
1-原生JS
获取属性 .getAttribute("属性")
2-jquery
获取属性 .attr("属性")
示例代码
/*jq获取属性*/ var temp = $(\'.test1\').attr(\'class\'); /*js获取属性*/ var temp = document.getElementById(\'test1\').getAttribute(\'data\');
二、设置元素的属性
1-原生JS
设置属性 .setAttribute("属性","值")
2-jquery
设置属性 .attr("属性","值")
实例代码
/*jq设置属性*/ var temp2= $(\'.test2\').attr(\'class\',\'test-spe\'); /*js设置属性*/ var temp2= document.getElementById(\'test2\').setAttribute(\'data\',\'self-name-2\');
三、删除元素的属性
1-原生JS
删除属性 .removeAttribute
2-jquery
删除属性 .removeAttr
示例代码
/*jq删除属性*/ var temp = $(\'.test1\').removeAttr(\'data\'); /*js删除属性*/ var temp = document.getElementById(\'test1\').removeAttribute(\'data\');
以上上面代码实例全部
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>元素属性</title> <style> * { margin:0; padding:0; list-style:none; } a{ color: #5579ee; cursor: pointer; } </style> </head> <body> <div id="mayouchen" style="width: 500px;margin: 50px auto;"> <a id="test1" class="test1">元素属性获取(class为test1)</a> <p><span>属性名:</span><span class="test1_2"></span></p> <br /> <a id="test2" class="test2">元素属性设置(修改class为test2的值为test-spe)</a> <p><span>设置的属性名:</span><span class="test2_2"></span></p> <br /> <a id="test3" class="test3" data="self-name">元素属性删除(删除data属性)</a> <p><span>删除属性名:</span><span class="test3_1"></span></p> </div> <script src="https://cdn.bootcss.com/jquery/1.8.3/jquery.min.js"></script> <script> $(\'.test1\').on(\'click\',function(){ /*jq获取属性*/ var temp = $(\'.test1\').attr(\'class\'); /*js获取属性*/ var temp = document.getElementById(\'test1\').getAttribute(\'class\'); console.log(temp); $(\'.test1_2\').text(temp); }) $(\'.test2\').on(\'click\',function(){ /*jq设置属性*/ var temp2= $(\'.test2\').attr(\'class\',\'test-spe\'); /*js设置属性*/ var temp2= document.getElementById(\'test2\').setAttribute(\'class\',\'test-spe\'); var temp_spe = $(\'.test-spe\').attr(\'class\'); $(\'.test2_2\').text(temp_spe); }) $(\'.test3\').on(\'click\',function(){ var tempSpe = $(\'.test3\').attr(\'data\'); /*jq删除属性*/ var temp = $(\'.test3\').removeAttr(\'data\'); /*js删除属性*/ var temp = document.getElementById(\'test3\').removeAttribute(\'data\'); console.log(tempSpe); $(\'.test3_1\').text(tempSpe); }) </script> </body> </html>
版权声明:本文为chengxs原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。