原型:选择包含文本的元素(如 jQuery :contains())

问题描述:

使用 Prototype 我必须选择并隐藏所有包含单词 Foo

  • 元素:

    Using Prototype I have to select and hide all <li> elements containing the word Foo inside:

    <li><label>Lorem Lipsum Foo</label></li>
    <li><label>Lorem Lipsum Bar</label></li>
    

    我知道使用 jQuery 就像 $('li:contains("Foo")').hide() 一样简单,但在 Prototype 中找不到方法.

    I know with jQuery it is as easy as $('li:contains("Foo")').hide(), but could not find a way to do that in Prototype.

  • var lis = document.getElementsByTagName("li");
    [].forEach.call(lis, function (li) {
      if (li.textContent.indexOf("Foo") > -1) {
        li.style.display = "none";
      }
    });
    

    说真的,您不需要为此使用库.只是一点点的 DOM4 &ES5 为您做到了.

    Seriously, you don't need libraries for this. Just a good bit of DOM4 & ES5 does it for you.

    如果您关心旧平台支持,请使用普通垫片

    Use the normal shims if you care about legacy platform support

    SideNote:永远不要做 $("li:contains('Foo')") 其异常缓慢的地狱.更不用说对选择器的残忍滥用4

    SideNote: don't ever do $("li:contains('Foo')") its epicly slow as hell. Not to mention murderous abuse of selectors4