简体   繁体   English

在文档中搜索带有样式名称的元素?

[英]Search the document for an element with a style name?

Is there a way to search the DOM for an element with a particular stylename class? 有没有办法在DOM中搜索具有特定stylename类的元素? Something like: 就像是:

var node = document.findByClassName("foo");

if so, will this be extremely slow if my page has like 2000 elements in it or so? 如果是这样的话,如果我的页面中有2000个元素,这会非常慢吗?

Thanks 谢谢

Well, jQuery has a class selector: 好吧, jQuery有一个类选择器:

$('.foo')

You can look there for an implementation. 您可以在那里查看实现。

Firefox supports a native getElementsByClassName() AFAIK. Firefox支持本机getElementsByClassName() AFAIK。

If the browser does not support the native method you can sift through every tag and look for the class names. 如果浏览器不支持本机方法,您可以筛选每个标记并查找类名。 This version allows you to specify a parent to search from and more than one class can be matched. 此版本允许您指定要搜索的父级,并且可以匹配多个类。 It returns an array of nodes in either case, not a 'live' nodelist. 它会返回一个节点数组,而不是“实时”节点列表。

function getbyClass(classes, pa){
    pa= pa && pa.nodeType== 1? pa: document;
    // native support:
    if(pa.getElementsByClassName){
        var A= [], N= pa.getElementsByClassName(classes);
        for(var i= 0, L= N.length; i<L; i++){
            A[i]= N[i];
        }
        return A;
    }
    // no native support:
    var elems= [], c= classes.split(/ +/), L= c.length, tem, temc,
    tags= pa.getElementsByTagName('*'), max= tags.length;
    for(var i= 0, L= c.length; i< L; i++){
        c[i]= RegExp('\\b'+c[i]+'\\b');
    }
    getbyClassloop: 
    while(max){
        i= L;
        tem= tags[--max];
        temc= tem.className;
        if(temc){
            while(i){
                if(!c[--i].test(temc)) continue getbyClassloop;
            }
            elems[elems.length]= tem;
        }
    }
    return elems;
}

// use- // 采用-

getbyClass('classname')
// searches document for elements with classname 

getbyClass('classname1 classname2')
// searches document for elements with both classes

getbyClass('classname1 classname2',containingelement)
// searches only containingelement and descendents

/*IE9 will have support for the native method, and versions of IE below 8, as well as some other older browsers, will fall back to the sifting method. / * IE9将支持本机方法,并且低于8的IE版本以及其他一些旧版浏览器将回退到筛选方法。 You can add a quicker method than the sifter to IE8. 您可以向IE8添加比sifter更快的方法。 */ * /

(function(){
    if(!document.getElementsByClassName && document.attachEvent){
        try{
            if(document.querySelectorAll){
                var IE8class= function(classes){
                    var C= classes.split(' '), tem,
                    els= Array.from(this.querySelectorAll('.'+ C.shift()));
                    while(C.length && els.length){
                        tem= C.shift();
                        els= els.testEach(function(itm){
                            return itm.className.indexOf(tem)!= -1;
                        });
                    }
                    return els;
                }
                HTMLDocument.prototype.getElementsByClassName= IE8class;
                Element.prototype.getElementsByClassName= IE8class;
                return true;
            }
        }
        catch(er){
            return false
        };
    }
})()

Many Ajax libraries provide this. 许多Ajax库提供了这一点。 For example YUI provides method 例如,YUI提供方法

YAHOO.util.Element.getElementsByClassName (class )

more details could be found here http://developer.yahoo.com/yui/docs/YAHOO.util.Element.html 更多细节可以在这里找到http://developer.yahoo.com/yui/docs/YAHOO.util.Element.html

I use it a lot and don't find any major slowdowns. 我经常使用它,并没有发现任何重大减速。

jQuery is free lightweight cross-browser script library. jQuery是免费的轻量级跨浏览器脚本库。

It has tons of cool features and selecting all elements with a class name is as easy as 它有很多很酷的功能,选择所有带有类名的元素都很简单

$('.foo');

Moreover, it comes with plenty of free plug-ins that will make your development job so easier. 此外,它还附带了大量免费插件,可以让您的开发工作变得更加轻松。

For example, following code does exactly what it reads: 例如,以下代码完全执行以下操作:

$("p.neat").addClass("ohmy").show("slow");

ie all p tags with neat class applied, add a new class ohmy and make it visible with slow animation. 即所有应用了整齐类的p标签,添加一个新类ohmy并使其以慢动画显示。 Cool eh? 很酷吗?

You can use SizzleJs , this is also whats used inside jQuery. 你可以使用SizzleJs ,这也是jQuery中使用的。

var elements = Sizzle(".foo"); var elements = Sizzle(“。foo”);

Alas, JavaScript doesn't natively include a function to do just that**. 唉,JavaScript本身并没有包含这样做的功能**。 Most JavaScript libraries do offer a simple way to select elements by class, but they each have their own pros and cons. 大多数JavaScript库确实提供了一种按类选择元素的简单方法,但它们各有各的优缺点。

If you don't want to use a JavaScript library (Which is fine; there are great reasons for not using additional libraries.), you could do something like this: 如果您不想使用JavaScript库(这很好;有很多理由不使用其他库。),您可以这样做:

elems = document.getElementsByTagName("h2");

for ( i=0; i<elems.length; i++ )
{
if ( elems[i].className == "myAwesomeClass" )
   { //  Do whatever stuff needs to happen to the class
     elems[i].style.color="red"; 
     }
}

In the above code, I've assumed that each element with the desired class has the same tag. 在上面的代码中,我假设每个具有所需类的元素具有相同的标记。 If necessary, you could do document.getElementsByTagName("*") to select all tags, but that would probably take longer for the browser to process. 如有必要,您可以使用document.getElementsByTagName(“*”)来选择所有标签,但浏览器可能需要更长时间才能处理。

** Correction / Clarification: Most recent browsers support document.getElementsByClassName. **更正/澄清:最新的浏览器支持document.getElementsByClassName。 IE8 does not. IE8没有。 ( http://www.quirksmode.org/dom/w3c_core.html#t11 ) http://www.quirksmode.org/dom/w3c_core.html#t11

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM