How to find element without use ID

前端 未结 5 376
甜味超标
甜味超标 2021-01-27 14:43

I have DOM element in array

this.object = 
     
\"color1 text1
5条回答
  •  遥遥无期
    2021-01-27 15:05

    You could use getElementsByClassName().

    document.getElementsByClassName("color")[0];
    

    But you have to remember two things: 1.) getElementsByClassName() is not fully cross-browser compatible. 2.) You have two know at what position your color element is. If you only using the class color once the example works perfectly.

    Two solve issue 1.) you can use following workaround:

    function getElementsByClassName(node, classname) {
        var a = [];
        var re = new RegExp('(^| )'+classname+'( |$)');
        var els = node.getElementsByTagName("*");
        for(var i=0,j=els.length; i

提交回复
热议问题