javascript - changing a class' style

前端 未结 5 1016
一整个雨季
一整个雨季 2020-12-15 18:33

I\'ve been working with jQuery for a while, but now I want to write something in pure javascript and it\'s prooving to be challenging.. One of my biggest problems at the mom

5条回答
  •  再見小時候
    2020-12-15 19:08

    You can use selector library, for example Sizzle: http://sizzlejs.com/ but if you want pure JS that I guess you are stuck with getting all the elements, and then programatically "handpicking" the ones that have classes you are interested in using RegEx like this for example:

    This is an equivalent of your JQuery oneliner:

    for( i in document.all) document.all[i].className && /\bpost-text\b/g.test(document.all[i].className) && (document.all[i].style.color = "red")
    

    :)

    If you don't need it in one line you can make it faster (and much more readable):

    var myClassName = "someClass";
    var regexp  = RegExp("\\b"+myClassName+"\\b/g");
    var elements = document.all;
    for( i in elements){
      var this_element = elements[i];
      if(regexp.test(this_element.className){
        this_element.style.color = "red";
      }
    }
    

    If "for( i in object)" doesn't work for you, just use classic for loop "for(var i = 0; i < elements.length; i++)".

    It could be 'beautified' a bit with the use of some slightly more advanced JS concepts (array function mappings, folding and such), which JS version are you coding agains? I guess it's not ECMA Script 5, right?

    Also, check out this question/answer Get All Elements in an HTML document with a specific CSS Class

提交回复
热议问题