HTML DOM-->获取属性节点
1.方法一:
获取官方定义的属性直接使用:
元素节点.属性名
得到元素对应属性的属性值
举例:获取placeholder的属性值
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>js_excise</title> <script src="./js/js_excise.js" type="text/javascript" charset="utf-8"></script> </head> <body style="height: 187.5rem;"> <input id="in" type="text" name="Text" placeholder="please your name"> <script type="text/javascript"> var js = document.getElementById('in') console.log(js.placeholder) </script> </body> </html>
输出:
修改对应属性的属性值:
元素节点.属性名=新的属性值
举例:将placeholder="please your name"改为‘please enter your name’
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>js_excise</title> <script src="./js/js_excise.js" type="text/javascript" charset="utf-8"></script> </head> <body style="height: 187.5rem;"> <button onclick="func()">更新</button> <input id="in" type="text" name="Text" placeholder="please your name"> <script type="text/javascript"> var js = document.getElementById('in') console.log(js.placeholder) function func(){ js.placeholder = 'please enter your name' console.log(js.placeholder) } </script> </body> </html>
输出:
2.方法二:
元素节点.getAttribute("属性名")
得到元素对应属性的属性值
注意:该方法还可以获取自定义属性
举例1:获取placeholder属性的值
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>js_excise</title> <script src="./js/js_excise.js" type="text/javascript" charset="utf-8"></script> </head> <body style="height: 187.5rem;"> <button onclick="func()">更新</button> <input id="in" type="text" name="Text" placeholder="please your name"> <script type="text/javascript"> var js = document.getElementById('in') console.log(js.getAttribute('placeholder')) </script> </body> </html>
输出:
举例2:获取自定义属性my的值
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>js_excise</title> <script src="./js/js_excise.js" type="text/javascript" charset="utf-8"></script> </head> <body style="height: 187.5rem;"> <button onclick="func()">更新</button> <input id="in" type="text" name="Text" placeholder="please your name" my='abner'> <script type="text/javascript"> var js = document.getElementById('in') console.log(js.getAttribute('my')) </script> </body> </html>
输出:
修改元素对应属性的属性值
元素节点.setAttribute("属性名",“新的属性值”)
举例:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>js_excise</title> <script src="./js/js_excise.js" type="text/javascript" charset="utf-8"></script> </head> <body style="height: 187.5rem;"> <button onclick="func()">更新</button> <input id="in" type="text" name="Text" placeholder="please your name" my='abner'> <script type="text/javascript"> var js = document.getElementById('in') console.log('my更改前:'+js.getAttribute('my')) function func(){ js.setAttribute('my','hello world') console.log('my更改后:'+js.getAttribute('my')) } </script> </body> </html>
输出:
心揣信念,梦想就在脚下!