javascript - 如何用javascript删除段落内容

标签 javascript html getelementbyid

我有一个段落想要删除其内容。

document.getElementById(id).innerHTML = "";

似乎不起作用。有没有人有更好的解决方案?

这是一个例子

<!DOCTYPE html>
<html>
<head>
<script>
document.getElementById("p").innerHTML = "";
</script>
</head>
<body>
<p id="p">
words
</p>
</body>
</html>

但段落中的文字并未被删除。预先感谢任何可以提供帮助的人。

最佳答案

<!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>

关于javascript - 如何用javascript删除段落内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20926073/

相关文章:

javascript - getElementById 在循环中导致未捕获的类型错误

javascript - Typescript 不知道 FormData 是什么

html - 如何使子菜单出现在左侧,而不是右侧

多个日期模式的 Javascript 日期验证器

javascript - 来自 JSON 文件的嵌套列表内容

javascript - 使用 .parent 选择 div

javascript - 如何更改在子类中有设置的宽度/高度元素

javascript - 为什么不显示消息 "Hello world!"?

javascript - removeChild() 只删除一个 li 元素

JavaScript InfoVis Toolkit 处理大量数据的能力