How to find element without use ID

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

I have DOM element in array

this.object = 
     
\"color1 text1
相关标签:
5条回答
  • 2021-01-27 14:58

    You would use this.element[i] to access any element in the array, and then you can access the children of those elements:

    this.element[0].childNodes[0].innerHTML = "paint one";
    
    0 讨论(0)
  • 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<j; i++)
            if(re.test(els[i].className))a.push(els[i]);
        return a;
    }
    
    0 讨论(0)
  • 2021-01-27 15:07

    You should use jquery and then you can write it like this:

    $('.color').html('updated text')
    
    0 讨论(0)
  • 2021-01-27 15:07

    You could use querySelectors:

    //find first element with class 'color' within a div
    //returns an element Node
    [yourdiv].querySelector('.color');
    //find all elements with class 'color' within a document
    //returns a nodeList
    document.querySelectorAll('.color');
    

    Or getElementsByClassName:

    //find first element with class 'color' within a div
    //returns a nodeList with 1 or more elements
    [yourdiv].getElementsByClassname('.color')[0];
    //find all elements with class 'color' within a document
    //returns a nodeList
    document.getElementsByClassName('.color');
    
    0 讨论(0)
  • 2021-01-27 15:10

    Use jQuery to avoid any cross browser issues. Assuming you have the div, use div.find('span:eq(1)');

    Working example.

    Working example for multiple items.

    Another example showing the text being updated.

    0 讨论(0)
提交回复
热议问题