如何使用JavaScript根据元素文本隐藏一个元素?

6
我是一名初级开发者,我想要隐藏由第三方JavaScript动态添加到页面的div元素,以达到美观的目的。
问题在于该div元素没有id属性;这是否可能?div元素是否具有根据加载顺序固有的属性?还是有什么方法可以搜索文本字符串并隐藏元素?
例如,根据其文本“happy New year”删除
happy New year

1
不是挑剔,但它实际上是一个HTML DOM元素。CSS没有元素,选择它们是通过元素名称、类名或ID完成的。选择引擎如JQuery使用类似CSS的语法来选择您想要的元素。 - Spoike
4个回答

9

你可以先选择相关元素,然后迭代它们直到找到你想要的。

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

请注意,代码有点脆弱,完全取决于元素的内容。以下是相关的 JQuery api 文档: 请注意,您可以更具体地选择您的选择器,例如您有以下代码:
<div class="message">
    <div>happy New year<div>
</div>

您可以使用以下方法选择元素:

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

嗨,Spoike!我尝试了以下代码,似乎无法隐藏div。 - user3180
@Richard 哎呀,括号打错了。这个 jsfiddle 上可以运行:http://jsfiddle.net/vU7Vn/ ,我已经编辑了答案。 - Spoike

3

我想提供一个纯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.


非常欢迎!希望对你和其他人在未来有所帮助。=) - David Thomas
1
这是一个非常棒的答案。我改变了基于字符串的布尔值,并稍微修改了reg正则表达式的构造。jsFiddle - tiffon
@tiffon:谢谢!那基本上就是我今晚的项目(当时回答时我没有太多时间);现在看起来我不必再费心了 =D - David Thomas

2
一个先前的答案将基于组合文本内容(请参阅.text()行为)隐藏一个节点。以下测试用例将说明这一点:
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>

这里显示:jsFiddle 根据您的情况细节,这种更一般的行为可能是您想要的,因为它将忽略后代结构,并仅匹配组合文本。但是,如果您需要隐藏特定包含文本的
,则以下内容将仅隐藏测试用例中的最后一个

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();

这里显示:jsFiddle 初始选择器可以修改为隐藏包含特定文本的任何内容。这种更一般的方法将在第一个示例中隐藏元素,在最后一个示例中隐藏
元素。
$(':contains(' + tx + ')').filter(// etc...

您可以考虑从DOM中移除该元素,而不只是隐藏它。 :contains() jQuery选择器 .filter() jQuery方法 .contents() jQuery方法 nodeType节点属性 .remove() jQuery方法

0

你实际上可以用一行代码来完成它

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接