Javascript 按 id 隐藏 HTML 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2420135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:14:22  来源:igfitidea点击:

Hide HTML element by id

javascripthtmlcss

提问by Adam Davis

Hopefully there's a quick and dirty way to remove the "Ask Question" (or hide it) from a page where I can only add CSS and Javascript:

希望有一种快速而肮脏的方法可以从我只能添加 CSS 和 Javascript 的页面中删除“提问”(或隐藏它):

  <div class="nav" style="float: right;">
      <ul>
          <li style="margin-right: 0px;" >
              <a id="nav-ask" href="/questions/ask">Ask Question</a>
          </li>
      </ul>
  </div>

I can't hide the navclass because other page elements use it.

我无法隐藏nav该类,因为其他页面元素使用它。

Can I hide the link element via the nav-askid?

我可以通过nav-askid隐藏链接元素吗?

采纳答案by jwhat

<style type="text/css">
  #nav-ask{ display:none; }
</style>

回答by Fermin

If you want to do it via javascript rather than CSS you can use:

如果你想通过 javascript 而不是 CSS 来做到这一点,你可以使用:

var link = document.getElementById('nav-ask');
link.style.display = 'none'; //or
link.style.visibility = 'hidden';

depending on what you want to do.

取决于你想做什么。

回答by Rob Allen

@Adam Davis, the code you entered is actually a jQuery call. If you already have the library loaded, that works just fine, otherwise you will need to append the CSS

@Adam Davis,您输入的代码实际上是一个 jQuery 调用。如果您已经加载了该库,则可以正常工作,否则您将需要附加 CSS

<style type="text/css">
    #nav-ask{ display:none; }
</style>

or if you already have a "hideMe" CSS Class:

或者如果您已经有一个“hideMe”CSS 类:

<script type="text/javascript">

    if(document.getElementById && document.createTextNode)
    {
        if(document.getElementById('nav-ask'))
        {
            document.getElementById('nav-ask').className='hideMe';
        }
    }

</script>

回答by Brant

.nav ul li a#nav-ask{
    display:none;
}

回答by Adam Davis

I found that the following code, when inserted into the site's footer, worked well enough:

我发现以下代码在插入到站点的页脚时运行良好:

<script type="text/javascript">
$("#nav-ask").remove();
</script>

This may or may not require jquery. The site I'm editing has jquery, but unfortunately I'm no javascripter, so I only have a limited knowledge of what's going on here, and the requirements of this code snippet...

这可能需要也可能不需要 jquery。我正在编辑的网站有 jquery,但不幸的是我不是 javascripter,所以我对这里发生的事情的了解有限,以及这段代码片段的要求......

回答by pixeltocode

you can use CSS selectors

你可以使用 CSS 选择器

a[href="/questions/ask"] { display:none; }