方法:1、使用“element.innerText=’值’”或“element.innerHTML=’值’”语句修改元素内容;2、使用“element.style”或“element.className”语句修改元素样式属性。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
操作修改元素
JavaScript的DOM操作可以改变网页内容、结构和样式,我们可以利用DOM操作元素来改变元素里面的内容、属性等。
改变元素的内容
element.innerText从起始位置到终止位置的内容,但它去除html标签,同时空格和换行也会去掉
element.innerHTML起始位置到终止位置的全部内容,包括html标签,同时保留空格和换行。
innerText不识别HTML标签,innerHTML识别HTML标签。这两个属性是可读写的。
<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>

运行后,显示某个时间,当点击显示系统当前时间即可显示进当前的日期及星期。

修改样式属性
element.style修改行内式操作,element.className修改类名样式属性
<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>
程序运行后,出现一个宽高均为200像素的粉红色盒子,点击盒子,变成宽300像素高200像素的紫色盒子。JS修改style样式操作,产生的是行内样式。
使用className更改样式属性
<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>
【相关推荐:javascript学习教程】
以上就是javascript怎么修改元素的详细内容,更多请关注其它相关文章!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
