如何获取所有的HTML属性(属性名称,*不*他们的值!) [英] How to get all HTML attributes which start with something (the attribute names, *not* their values!)

查看:134
本文介绍了如何获取所有的HTML属性(属性名称,*不*他们的值!)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望得到一个HTML页面中包含属性的所有元素/节点,这些属性从某些东西开始(同样,属性名称以某些东西开头,而不是它们的值!)。例如,TinyMCE具有向其保存的元素添加自定义属性的趋势,如mce_stylemce_hrefmce_bogus等等。我想要像属性值的CSS3选择器, [attr ^ =mce _] 但不是值,属性名称

I would like to get all the elements/nodes in an HTML page which contain attributes that start with something (again, the attribute names start with something, not their values!). For example, TinyMCE has a tendency of adding custom attributes to the elements it saves, like "mce_style", "mce_href", "mce_bogus", etc. I would like to have something like the CSS3 selector for attribute values, [attr^="mce_"], but not for the values, the attribute names.

当然,我可以遍历所有DOM节点他们的属性并逐一检查,但我想知道是否有更有效的方式。

Of course, I can iterate through all DOM nodes and their attributes and check them one by one, but I was wondering whether there is a more efficient way.

请不要给我TinyMCE的具体答案,我是相当肯定有一个标志,这将是TinyMCE保存这些属性的标志,但问题是通用的。

Please don't give me TinyMCE-specific answers, I'm pretty sure there's a flag which would precent TinyMCE for saving these attributes, but the question is generic.

推荐答案

这是一个简单的演示,以查找包含以 mce _ 。可能需要一些细化。

here's a simple demo to find all elements that contain an attribute starting with mce_. might need some refinements.

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

这篇关于如何获取所有的HTML属性(属性名称,*不*他们的值!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆