尝试使用JavaScript删除HTML元素 [英] Trying to remove HTML-element using JavaScript

查看:81
本文介绍了尝试使用JavaScript删除HTML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果访问我的网站的设备的宽度为< 320,我希望删除< h3> 。这是我试过的:

HTML:

  < HEAD> 
< script type =text / javascriptsrc =javascript.js>< / script>
< / head>
< body>
< h3 id =title>标题< / h3>
< / body>

JavaScript:

  if(document.documentElement.clientWidth< = 320){

document.write(Testing);

var h3 = document.getElementById(title);

h3.parentNode.removeChild(h3);

$ / code>

测试标签打印在屏幕上,但< h3> 仍然存在。怎么了?

解决方案

当脚本执行时, h3 未被分析,所以它不存在于DOM中。



将删除它的那部分脚本移到 h3 在HTML中。



更好的是,忘记使用JavaScript并使用媒体查询 h3 {display:none; } 改为。


If width of the device visiting my site is <320 I want a <h3> to be removed. This is what I've tried with:

HTML:

<head>
    <script type="text/javascript" src="javascript.js"></script>
</head>
<body>
    <h3 id="title">Title</h3>
</body>

JavaScript:

if (document.documentElement.clientWidth <= 320) {

    document.write("Testing");

    var h3 = document.getElementById("title");

    h3.parentNode.removeChild(h3);
}

The "testing" label is printed on the screen but the <h3>is still there. What's wrong?

解决方案

At the time the script is executed, the h3 element has not been parsed, so it doesn't exist in the DOM.

Move the part of the script that removes it to after the h3 in the HTML.

Better yet, forget about using JavaScript and use media queries with h3 { display: none; } instead.

这篇关于尝试使用JavaScript删除HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆