Method: 1. Use the "element.innerText='value'" or "element.innerHTML='value'" statement to modify the element content; 2. Use the "element.style" or "element.className" statement Modify element style properties.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
JavaScript's DOM operation can change the content, structure and style of the web page. We can use DOM operation elements to change the content, attributes, etc. inside the element.
Change the content of the element
element.innerText
The content from the starting position to the ending position, But it removes the html tag, and at the same time, the spaces and line breaks will also be removed. All the content from the starting position to the end position of
element.innerHTML
, including the html tag, while retaining the spaces and line breaks.
innerText does not recognize HTML tags, innerHTML recognizes HTML tags. These two properties are readable and writable.
<body> <button> 显示系统当前时间 </button> <div> 某个时间 </div> <script> var btn = document.querySelector('button'); var div = document.querySelector('div'); btn.onclick = function(){ div.innerText = getDate(); } function getDate(){ var date = new Date(); var year = date.getFullYear(); var month = date.getMonth()+1; var dates = date.getDate(); var arr = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六']; var day = date.getDay(); return '今天是'+year+'年'+month+'月'+dates+'日'+arr[day]; } </script> </body>
After running, a certain time will be displayed. When you click to display the current system time, the current date and week will be displayed.
Modify style attributes
element.style modifies the inline operation, element.className modifies the class name Style attribute
<head> <style> div { width:200px; height:200px; background-color:pink; } </style> </head> <body> <div> </div> <script> var div = document.quertSelector('div'); div.onclick = function(){ this.style.backgroundColor = 'purple'; this.style.width='300px'; } </script> </body>
After the program is run, a pink box with a width and height of 200 pixels will appear. Click the box to turn it into a purple box with a width of 300 pixels and a height of 200 pixels. JS modifies the style style operation and produces inline styles.
Use className to change style attributes
<head> <style> div { width:100px; height:100px; background-color:pink; } .change { width:200px; height:200px; background-color:purple; } </style> </head> <body> <div> 文本 </div> <script> vet test =document.querySelector('div'); test.onclick = function(){ //将当前元素的类名改为change this.className = 'change'; } </script> </body>
[Related recommendations: javascript learning tutorial]
The above is the detailed content of How to modify elements in javascript. For more information, please follow other related articles on the PHP Chinese website!