扫描 DOM 并返回或操作具有以特定字符串为前缀的特定属性的元素

Scan DOM and return or manipulate elements that have specific attributes prepended with specific string

本文关键字:元素 字符串 前缀 属性 返回 DOM 操作 扫描      更新时间:2023-09-26

我正在尝试弄清楚如何从 DOM 中获取元素列表(从上到下(,其中包含以给定字符串为前缀的特定属性,例如"猴子"是该字符串。如果存在的话。

我用$.each():contains把这个非常松散的想法放在一起,但在两者之间,我认为它没有任何好处。所以我想我来这里是为了挑选几个大脑。

我想做的基本上是在调用我最终将建立的给定函数时扫描我的 dom。这将寻找带有属性前缀的元素,在这种情况下,"猴子"想到data-属性及其用法。减去提供特定的选择器,而不是实际使用 data- 属性。

想象一下这个 HTML

<div monkey-user="bar" monkey-permission="read">
    <span monkey-user="bar" monkey-permission="read">some text</span>
</div>
<div>
    <input type="text" monkey-user="bar" monkey-permission="none">
</div>
<input type="text">
<input type="text">
<input type="text">
<input type="text">

然后是这个JavaScript/jquery概念,除非可以使用更干净的东西。

var arr = new Array();
$("*").each(function()
    {
     if($(this).children().length == 0) 
         {
              if($(':contains("monkey-")',this))
              {
                 arr.push($(this));
              }   
         }
 });

在这种情况下,arr 的结果将是上面的 3 个元素,其中有monkey-,否则会跳过任何其他元素。 还值得注意的是,用户/权限是为了示例,从长远来看,这些可以是其他特定的东西,将根据需要使用(在这种情况下,这些将类似于使用 data 属性,但我认为这将是另一个问题,没有人想把它作为奖励扔进去。

你可以试试这种方式:

var arr = $("body").find('*').filter(function(){
    var attrs = this.attributes; //get the attributes of the element
    return ($.grep(attrs, function(o){
        return /monkey/.test(o.name); //return the attributes that has name to be matched
    }).length); //return the elements that has at least one of the matched attributes
}).get();
console.log(arr);

小提琴

但请注意,这些属性名称对 html 元素无效。请考虑改用data-*属性

如果您打算使用 data-*,那么您可以使用数据 api(但这也会选择其他数据属性集,这些属性不是元素的属性(

var arr = $("body").find('*').filter(function(){
    var attrs = Object.keys($(this).data());
    return ($.grep(attrs, function(o){
        return /monkey/.test(o) === true;
    }).length);
}).get();

小提琴

但是这些方法确实会减慢速度并且效率低下,我建议您添加另一个属性,例如data-hasmonkey具有您的猴子属性的所有属性。然后,您可以使属性选择器更简单、更好:$("[data-hasmonkey]");