如何获取所有以某物开头的HTML属性(属性名称,*不是*它们的值!

How to get all HTML attributes which start with something (the attribute names, *not* their values!)

本文关键字:属性 不是 HTML 开头 获取 何获取      更新时间:2023-09-26

我想获取HTML页面中的所有元素/节点,其中包含以某物开头的属性(同样,属性名称以某物开头,而不是它们的值!例如,TinyMCE倾向于将自定义属性添加到它保存的元素中,如"mce_style""mce_href""mce_bogus"等。我想要类似 CSS3 属性值的选择器,[attr^="mce_"]但不用于值,属性名称

当然,我可以遍历所有 DOM 节点及其属性并逐个检查它们,但我想知道是否有更有效的方法。

请不要给我 TinyMCE 特定的答案,我很确定有一个标志会阻止 TinyMCE 保存这些属性,但问题是通用的。

这里有一个简单的演示,用于查找包含以 mce_ 开头的属性的所有元素。 可能需要一些改进。

function getMCE() {
    var el, attr, i, j, arr = [],
        reg = new RegExp('^mce_', 'i'),                //case insensitive mce_ pattern
        els = document.body.getElementsByTagName('*'); //get all tags in body
    for (i = 0; i < els.length; i++) {                 //loop through all tags
        el = els[i]                                    //our current element
        attr = el.attributes;                          //its attributes
        dance: for (j = 0; j < attr.length; j++) {     //loop through all attributes
            if (reg.test(attr[j].name)) {              //if an attribute starts with mce_
                arr.push(el);                          //push to collection
                break dance;                           //break this loop
            }
        }
    }
    return arr;
}
console.log(getMCE())​

试试这个:

功能

//custom selector expression
$.extend($.expr[':'],{
attr:function(o,i,m){
  var attrs=$.getAttrAll(o),re=m[3],found=false;
  $.each(attrs,function(k,v){
  if(new RegExp(re).test(v)) { return found=true;}
});
return found;
} 
});
// get all atrributes of an element
$.getAttrAll=function(el){
  var rect = [];
  for (var i=0, attrs=el.attributes, len=attrs.length; i<len; i++){
    rect.push(attrs.item(i).nodeName);
  }
  return rect;
};

'用法

// calling custom selector expression :attr(regexp)
$(function(){
  $('body').find(':attr("^mce_")').css({background:'yellow'});
});

.HTML

<body>
  <p mce_style="height:50px" id="x" data-hello="hello">selected</p>
  <div not_mce_bogus="abc">not_mce_bogus</div>
  <div mce_href="http://rahenrangan.com">selected</div>
  <p>othrs</p>
</body>

如果您不介意暂时更改 DOM,一种选择是将 HTML 提取为字符串并通过 RegEx 搜索属性。 当你找到属性时,你可以在 DOM 中附加一个"针",以便你可以使用 jQuery 来选择元素。

这是一个工作概念(在控制台打开的情况下运行):

http://jsfiddle.net/skylar/N43Bm/

法典:

$.fn.extend({
    findAttributes: function(attribute) {
        var attributeFinder = new RegExp(attribute + '(.+)="', "gi");
        var elementHTML = this.html().replace(attributeFinder, "data-needle='pin' "+attribute+"$1='"");
        this.html(elementHTML);
        return this.find("[data-needle=pin]").removeAttr('data-needle');
    }
});
console.log($("body").findAttributes('mce_'));

注意:我的正则表达式不是很好。 在这个例子中,你必须比我更小心。

试试这个:(我尝试放置*而不是a标签,但它为所有元素着色,包括那些没有mce_style属性的元素)

a[mce_style] { color : red; }​

演示 : http://jsfiddle.net/Tcdmb/

更多信息 : https://developer.mozilla.org/en/CSS/Attribute_selectors