最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - javascript modify css class property while knowing only the class' name - Stack Overflow

programmeradmin0浏览0评论

Here's my css class:

.my-css-class-name
{
    display: block;
}

And I have one element at my webpage that uses this class. I want to modify this element's "display" property.
I would happily do this by getting a handle to that element and then modifying what I need, BUT, I don't know the element's name - it's being randomly generated (it's a third-party extension).

So I figured I'm gonna have to get a handle to ".my-css-class-name" and modify that property directly.
How do I get there, cross-browser (major ones) solution?

Edit #1:
I'm looking for patibility with newer browsers.

Here's my css class:

.my-css-class-name
{
    display: block;
}

And I have one element at my webpage that uses this class. I want to modify this element's "display" property.
I would happily do this by getting a handle to that element and then modifying what I need, BUT, I don't know the element's name - it's being randomly generated (it's a third-party extension).

So I figured I'm gonna have to get a handle to ".my-css-class-name" and modify that property directly.
How do I get there, cross-browser (major ones) solution?

Edit #1:
I'm looking for patibility with newer browsers.

Share Improve this question edited Dec 14, 2010 at 15:06 user113716 323k64 gold badges453 silver badges441 bronze badges asked Dec 14, 2010 at 14:26 PoniPoni 11.3k28 gold badges83 silver badges125 bronze badges 6
  • Using any javascript framework? Jquery, Mootools etc? – Mark Grey Commented Dec 14, 2010 at 14:30
  • is it being randomly generated in a way that a well crafted regex could catch? – Matt Phillips Commented Dec 14, 2010 at 14:30
  • @DeaconDesperado I have no clue about js frameworks although I do know this element is being generated by jQuery. – Poni Commented Dec 14, 2010 at 14:38
  • @Matt its id is a random number which I doubt any regex can catch/predict it. Since I don't know if it's "pure" random number I don't want to take the risk and rather simply change the css rule. – Poni Commented Dec 14, 2010 at 14:39
  • @Poni: Since jQuery seems to be loaded, you should use it. Its browser patibility is one of its most pelling features. – user113716 Commented Dec 14, 2010 at 14:56
 |  Show 1 more ment

5 Answers 5

Reset to default 5

Well, theoretically, it's easy.

document.getElementsByClassName("my-css-class-name")[0].style.display = "something";

In case you need IE patibility:

/*
    Developed by Robert Nyman, http://www.robertnyman.
    Code/licensing: http://code.google./p/getelementsbyclassname/
*/
var getElementsByClassName = function (className, tag/* "a","div",... */, elm/*parent*/){
    if (document.getElementsByClassName) {
        getElementsByClassName = function (className, tag, elm) {
            elm = elm || document;
            var elements = elm.getElementsByClassName(className),
                nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
                returnElements = [],
                current;
            for(var i=0, il=elements.length; i<il; i+=1){
                current = elements[i];
                if(!nodeName || nodeName.test(current.nodeName)) {
                    returnElements.push(current);
                }
            }
            return returnElements;
        };
    }
    else if (document.evaluate) {
        getElementsByClassName = function (className, tag, elm) {
            tag = tag || "*";
            elm = elm || document;
            var classes = className.split(" "),
                classesToCheck = "",
                xhtmlNamespace = "http://www.w3/1999/xhtml",
                namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
                returnElements = [],
                elements,
                node;
            for(var j=0, jl=classes.length; j<jl; j+=1){
                classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
            }
            try {
                elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
            }
            catch (e) {
                elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
            }
            while ((node = elements.iterateNext())) {
                returnElements.push(node);
            }
            return returnElements;
        };
    }
    else {
        getElementsByClassName = function (className, tag, elm) {
            tag = tag || "*";
            elm = elm || document;
            var classes = className.split(" "),
                classesToCheck = [],
                elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
                current,
                returnElements = [],
                match;
            for(var k=0, kl=classes.length; k<kl; k+=1){
                classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
            }
            for(var l=0, ll=elements.length; l<ll; l+=1){
                current = elements[l];
                match = false;
                for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
                    match = classesToCheck[m].test(current.className);
                    if (!match) {
                        break;
                    }
                }
                if (match) {
                    returnElements.push(current);
                }
            }
            return returnElements;
        };
    }
    return getElementsByClassName(className, tag, elm);
};

getElementsByClassName("my-css-class-name")[0].style.display = "something";

Following your response in the ment, if the element is being generated by Jquery, then the library is most likely installed. Here is something you can try to select it via Jquery and change the require property.

$(document).ready( function(){    
$('.my-class-name').css('display', 'block');
});

Substituting 'block' for whatever setting you require.

If Jquery is included it should do what your require on page load. You can also attach it to other events as well.

$(document).ready(function(){
$('.my-class-name').click(classClicked);
})

function classClicked(){
$(this).css('display','block')
}

getElementByClassName is not possible (in older browsers) but there are work arounds including iterating through every element. See here for discussion Do we have getElementsByClassName in javascript?

Some newer browsers support document.getElementsByClassName right out of the box. Older browsers do not and you have to use a function that loops through the elements of the page.

A flexible getElementsByClassName function with support for browser versions that do not support the native function as thejh suggested may be what you are looking for. It would work, at least. However, for what you are doing, it may be useful to look at the document.styleSheets property. With this route, you can change the CSS rule directly, which, if it worked consistently across browsers, would be the better route here. Unfortunately, browser patibility in this area is far from consistent, as shown here: http://www.quirksmode/dom/w3c_css.html

If you are still interested, have a look at this question: Changing a CSS rule-set from Javascript

发布评论

评论列表(0)

  1. 暂无评论