Selecting a div by classname

半腔热情 提交于 2019-11-26 17:25:07

问题


I got this div...

<div tabindex="0" class="button-base inline-block button aw-btn button-base-active">
    <input type="text" tabindex="-1" style="opacity: 0; height: 1px; width: 1px; z-index: -1; overflow-x: hidden; overflow-y: hidden; position: absolute; ">
 </div>

in the middle of my page, it has no id and I am unable to edit the pages HTML, I am also no able to use jQuery. Also trying to do it with IE7 and IE8.

Nightmare here :)

The solution would be document.getElementsByClassName but that is not ie7 and ie8 compatible.

This div is buried in about 10 divs, all of which are similar style with no id's etc. The classes on this div are unique!

The only solution I can see is to get ALL divs and loop them looking for hasAttriutes similar.

Anyone have a better idea?


回答1:


Here's a cross-browser implementation of getElementsByClassName for non-compliant browsers (citation):

if (!document.getElementsByClassName)
{

    document.getElementsByClassName = function(classname)
    {
        var elArray = [];

        var tmp = document.getElementsByTagName("*");

        var regex = new RegExp("(^|\\s)" + classname + "(\\s|$)");
        for ( var i = 0; i < tmp.length; i++ ) {

            if ( regex.test(tmp[i].className) ) {
                elArray.push(tmp[i]);
            }
        }

        return elArray;

    };
}



回答2:


Nope, that's how it's done. Unless they're in something with an ID you're stuck iterating all DIVs on the page. Fortunately it is just a list though (no need to recurse through a tree) so it's not so bad.




回答3:


I would suggest using XPaths to select the nodes. Might work...




回答4:


Use jQuery/Sizzle. IE6 and up. :)

Load it:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

Use it:

jQuery('.class.otherclass.anotherclass')


来源:https://stackoverflow.com/questions/5149522/selecting-a-div-by-classname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!