如何使用JavaScript隐藏基于文本的元素? [英] How to hide an element, based on its text, with JavaScript?

查看:80
本文介绍了如何使用JavaScript隐藏基于文本的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是初学者。我试图隐藏一个由第三方JavaScript动态添加到页面的div,用于审美目的。

I'm a beginner developer. I'm trying to hide a div that is dynamically added to the page by a 3rd party JavaScript for aesthetic purposes.

问题是div没有 id 属性;这有可能吗? div是否根据它们加载的顺序具有任何固有属性?或者有没有办法搜索一串文字并隐藏元素?

The problem is that the div has no id attribute; is this even possible? Do divs have any inherent attributes based on the order in which they load? Or is there any way to search for a string of text and hide the element?

例如,删除< div>新年快乐< / div> 根据其文字新年快乐

For example, removing <div>happy New year</div> based on its text happy New year.

推荐答案

您可以先选择相关元素并迭代它们,直到找到所需内容。

You can select the relevant elements first and iterate through them until you find what you want.

在JQuery中可以这样做:

In JQuery it can be done like this:

// select relevant elements
var elements = $('div');

// go through the elements and find the one with the value
elements.each(function(index, domElement) {
    var $element = $(domElement);

    // does the element have the text we're looking for?
    if ($element.text() === "happy New year") {
        $element.hide();
            // hide the element with jQuery
        return false; 
            // jump out of the each
    }
});

请注意,代码有点脆弱,完全取决于元素的内容。以下是相关的JQuery api文档:

Note that the code is a bit brittle and completely depends on the contents of the elements. Here are the relevant JQuery api docs:

  • Selectors in jQuery ($(...))
  • jQuery.each() - for going through the jquery objects array
  • jQuery.text() - for getting the value (there are small but noticable discrepancies between the browsers on how you do this in plain javascript)
  • jQuery.hide() - for hiding the element with CSS style display: none

请注意,您可以根据自己的选择更具体地说明您有以下代码:

Note that you can be more specific with your selection say you have the following code:

<div class="message">
    <div>happy New year<div>
</div>

您可以选择以下元素:

var domElement = $('.message div')[0]; // hopefully it only happens once

这篇关于如何使用JavaScript隐藏基于文本的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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