How to get class name through JavaScript

前端 未结 4 1000
[愿得一人]
[愿得一人] 2020-12-21 00:35

How do I get the class name through JavaScript given no id with this span.

Like:

I want to

相关标签:
4条回答
  • 2020-12-21 01:06

    Something like this should work:

    var spans = document.getElementsByTagName("span");
    for (var i = 0; i < spans.length; i++) {
        if (spans[i].className == 'xyz') {
            spans[i].style.backgroundColor = '#000';
        }
    }
    
    0 讨论(0)
  • 2020-12-21 01:08

    You have the following choices:

    1. Use document.getElementsByClassName("xyz"). This will return a NodeList (like an array) of objects that have that class name. Unfortunately, this function does not exist in older versions of IE.
    2. Use document.getElementsByTagName("span") and then loop over those objects, testing the .className property to see which ones have the desired class.
    3. Use document.querySelectorAll(".xyz") to fetch the desired objects with that class name. Unfortunately this function does not exist in older browsers.
    4. Get a library that automatically handles all CSS3 selector queries in all browsers. If you want just a selector library, then you can use Sizzle. If you want a more comprehensive library for manipulating the DOM, then use YUI3 or jQuery (both of which have Sizzle built-in).

    My advice is option #4. Unless this is a very small project, your development productivity will improve immensely by using a CSS3 selector library that has already been developed for cross-browser use. For example in Sizzle, you can get an array of objects with your class name with this line of code:

    var list = Sizzle(".xyz");
    

    In jQuery, you can create a jQuery object that contains a list of objects with that class with this line of code:

    var list = $(".xyz");
    

    And, both of these will work in all browsers since IE6 without you having to worry about any browser compatibility.

    0 讨论(0)
  • 2020-12-21 01:11

    You can use document.getElementsByClassName('xyz'). Note: it returns an array a NodeList (thanks to @IAbstractDownvoteFactory) since there can be multiple elements with the same class.

    var spans = document.getElementByClassName('xyz');
    var i;
    for(i=0; i<spans.length; i++) {
        spans[i].style.backgroundColor = your_color;
    }
    
    0 讨论(0)
  • 2020-12-21 01:28

    You can use a jquery to solve the same issue.

     var classname = $(this).attr('class'); //here you will get current class name if its with multiple class split it and take first class.
       $("."+classname.split(" ")[0]).css("background-color", "yellow");
    
    0 讨论(0)
提交回复
热议问题