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

时间:2012-04-25 09:56:25

标签: javascript dom selector

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

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

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

4 个答案:

答案 0 :(得分:5)

here's a simple demo查找包含以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())​

答案 1 :(得分:1)

试试这个:

<强>功能

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

` 的 USAGE

// 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>

答案 2 :(得分:1)

如果您不介意暂时更改DOM,可以选择将HTML解压缩为字符串并通过RegExp搜索属性。找到属性后,可以在DOM中附加“needle”,以便可以使用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_'));

注意:我的正则表达式不是很好。你必须采取比我在这个例子中更好的照顾。

答案 3 :(得分:-1)

试试这个:(我尝试使用*代替a代码,但它会为所有元素着色,包括那些没有mce_style属性的元素

a[mce_style] { color : red; }​

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

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