我有一个段落,我想删除。
的内容document.getElementById(id).innerHTML = "";
似乎没有用。有没有人有更好的解决方案?
这是一个例子
<!DOCTYPE html>
<html>
<head>
<script>
document.getElementById("p").innerHTML = "";
</script>
</head>
<body>
<p id="p">
words
</p>
</body>
</html>
但不删除段落中的字词。提前感谢任何可以提供帮助的人。
答案 0 :(得分:4)
<!DOCTYPE html>
<html>
<head>
<!-- here the p tag doesn't exist yet -->
<script>
document.getElementById("p").innerHTML = "";
</script>
</head>
<body>
<p id="p">
words
</p>
<!-- however here it does exist -->
</body>
</html>
如何解决?
// only use this if you can't move your javascript at the bottom
window.onload = function() {
document.getElementById("p").innerHTML = "";
}
或在页面末尾移动你的javascript(这是首选的,因为javascript应始终在页面末尾加载)
<!DOCTYPE html>
<html>
<head>
<!-- here the p tag doesn't exist yet -->
</head>
<body>
<p id="p">
words
</p>
<!-- however here it does exist -->
<script>
document.getElementById("p").innerHTML = "";
</script>
</body>
</html>
答案 1 :(得分:0)
请注意,您使用的不是W3C规范......(通过innerHTML =''删除)
var elem = document.getElementById(id);
if (!elem) {
console.log("No element for id:"+id);
} else {
elem.innerHTML="";
console.log("Should work");
}
答案 2 :(得分:0)
使它成为一个函数并添加body onload事件它应该工作:
<script>
function empty(){
document.getElementById("p").innerHTML = "";
}
</script>
<body onload='empty()'>
<p id="p">
words
</p>
</body>
答案 3 :(得分:0)
我经常使用jQuery来实现这个功能,但是,因为你正在寻找纯粹的javascript语法。你会想要使用这段代码:
document.getElementById("p").remove();
答案 4 :(得分:0)
<mat-form-field class="example-full-width">
<mat-label>Preferred Job</mat-label>
<mat-select>
<mat-option *ngFor="let job of filteredDesignationList('Designation') [value]="job.id">
{{job.lookupValue}}
</mat-option>
</mat-select>
</mat-form-field>
function funboi()
{
document.getElementById("p").innerHTML = "";
}