简体   繁体   English

如何使用JavaScript隐藏基于文本的元素?

[英]How to hide an element, based on its text, with JavaScript?

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. 我试图隐藏一个由第三方JavaScript动态添加到页面的div,用于审美目的。

The problem is that the div has no id attribute; 问题是div没有id属性; is this even possible? 这有可能吗? Do divs have any inherent attributes based on the order in which they load? div是否根据它们加载的顺序具有任何固有属性? Or is there any way to search for a string of text and hide the element? 或者有什么方法可以搜索一串文本并隐藏元素吗?

For example, removing <div>happy New year</div> based on its text happy New year . 例如,根据文本happy New year <div>happy New year</div>删除<div>happy New year</div>

You can select the relevant elements first and iterate through them until you find what you want. 您可以先选择相关元素并迭代它们,直到找到所需内容。

In JQuery it can be done like this: 在JQuery中,它可以像这样完成:

// 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
    }
});

Note that the code is a bit brittle and completely depends on the contents of the elements. 请注意,代码有点脆弱,完全取决于元素的内容。 Here are the relevant JQuery api docs: 以下是相关的JQuery api文档:

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>

You can select the element with: 您可以选择以下元素:

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

I thought I'd offer a plain-JavaScript alternative, which could be improved (quite a bit), particularly the passing of Booleans as strings (which feels hideous): 我以为我会提供一个简单的JavaScript替代方案,可以改进(相当多),特别是将布尔值作为字符串传递(感觉很可怕):

function hideByText(text, opts) {
    if (!text) {
        return false;
    }
    else {
        var defaults = {
            // the element we look within, expects:
            // 1: node reference, eg the result of: document.getElementsByTagName('div')[0]
            // 2: an element's id, as a string, eg: 'test'
            'within': document.body,
            // the element type, eg 'div', 'span', 'p', defaults to *everything*
            'elemType': '*',
            // case-sensitivity, as a string:
            // 'true' : is case sensitive, 'Some' will not match 'some',
            // 'false' : is case insensitive, 'Some' will match 'some'
            'sensitive': 'true',
            // 'absolute' : 'some text' will not match 'some text.'
            // 'partial' : 'some text' will match 'some text.'
            'match': 'absolute',
            // 'true' : removes white-space from beginning, and end, of the text,
            // 'false' : does not remove white-space
            'trim': 'true',
            // the class to add to elements if a match is made,
            // use CSS to hide, or style, the matched elements
            'matchedClass': 'hasText'
        },
            opts = opts || {};

        for (var setting in defaults) {
            if (defaults.hasOwnProperty(setting)) {
                opts[setting] = opts[setting] || defaults[setting];
            }
        }

        var within = opts.within.nodeType == 1 ? opts.within : document.getElementById(opts.within),
            elems = within.getElementsByTagName(opts.elemType),
            flags = opts.sensitive == 'true' ? 'i' : '',
            needle = opts.trim == 'true' ? text.replace(/^(\s+) || (\s+)$/g, '') : text,
            haystack,
            reg = new RegExp(needle, flags);

        if (opts.match == 'absolute') {
            for (var i = 0, len = elems.length; i < len; i++) {
                if ((elems[i].textContent || elems[i].innerText) == text) {
                    elems[i].className = opts.matchedClass;
                }
            }
        }
        else if (opts.match == 'partial') {
            for (var i = 0, len = elems.length; i < len; i++) {
                if ((elems[i].textContent || elems[i].innerText).match(reg)) {
                    elems[i].className = opts.matchedClass;
                }
            }
        }
    }
}

hideByText('some text', {
    'match': 'partial',
    'sensitive': 'true',
    'elemType': 'p',
    'matchedClass' : 'hasText'
});​

JS Fiddle demo . JS小提琴演示

A previous answer will hide a node based on the combined text content ( see .text() behavior ). 之前的答案将根据组合的文本内容隐藏节点( 请参阅.text()行为 )。 The following test cases will illustrate this: 以下测试用例将说明这一点:

should stay: <div><em>happy New year</em></div><br>
should stay: <div>happy New years</div><br>
should stay: <div>happy New <em>year</em></div><br>
should stay: <div>Something else entirely</div><br>
should hide: <div>happy New year</div>

Shown here: jsFiddle 如图所示: jsFiddle

Depending on the details of your situation, this more general behavior may be what you want as it will ignore descendant structure and only match against the combined text. 根据您的情况的详细信息,这种更一般的行为可能是您想要的,因为它将忽略后代结构并且仅匹配组合文本。 But, if you need to hide the <div> that specifically contains the text, something like the following will hide only the last <div> from the test cases: 但是,如果您需要隐藏专门包含文本的<div> ,则以下内容将仅隐藏测试用例中的最后一个<div>

var tx = 'happy New year';
$('div:contains(' + tx + ')').filter(function(){
    var $content = $(this).contents();
    return $content.length === 1 && 
        $content[0].nodeType === 3 &&
        $content.text() === tx;
}).hide();

Shown here: jsFiddle 如图所示: jsFiddle

The initial selector can be modified to hide anything that contains the specific text. 可以修改初始选择器以隐藏包含特定文本的任何内容。 This more general approach will hide the <em> element in the first case and the <div> element in the last case: 这种更通用的方法将隐藏第一种情况下的<em>元素和最后一种情况下的<div>元素:

$(':contains(' + tx + ')').filter(// etc...

You might consider removing the element from the DOM instead of only hiding it. 您可以考虑从DOM中删除元素,而不是仅隐藏它。

:contains() jQuery selector :contains() jQuery选择器

.filter() jQuery method .filter() jQuery方法

.contents() jQuery method .contents() jQuery方法

nodeType Node property nodeType节点属性

.remove() jQuery method .remove() jQuery方法

你实际上可以用一行来做

$("div").text("happy New year").hide(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM