0

I searched online for the correct syntax to reference a CSS class, instead of an HTML element, but was unable to find anything helpful.

I would like to modify the code below to reference any DIV of class buy_content "div.buy_content" instead of the body element.

<a href="#" onclick="body.style.fontSize='1em'; set_cookie('page_size', '1', 30);">Small Text</a>
<a href="#" onclick="body.style.fontSize='2em'; set_cookie('page_size', '2', 30);">Medium Text</a>
<a href="#" onclick="body.style.fontSize='3em'; set_cookie('page_size', '3', 30);">Large Text</a>
1
  • 2
    You don't need "javascript:" for "onclick" attribute values. Commented May 22, 2011 at 18:53

6 Answers 6

3

There is no "JavaScript syntax" for what you're asking for. Newer browsers support an API called "getElementsByClassName", so you could do this:

function setSize(sz) {
  var elements = document.getElementsByClassName('buy_content');
  for (var i = 0; i < elements.length; ++i) {
    if (elements[i].tagName === 'DIV')
      elements[i].style.fontSize = sz;
  }
}

<a href='#' onclick='setSize("1em"); set_cookie(...);'>Small</a>

You can find a "patch" for "getElementsByClassName" support here.

Sign up to request clarification or add additional context in comments.

4 Comments

Recommend querySelectorAll over getElementsByClassName since IE8 supports the former.
There are ways in javascript to do EXACTLY what he asked for (referencing CSS and it's classes). I described precisely what he asked in my answer.
Well sure, but that's not "JavaScript syntax". In other words, JavaScript runtime facilities in a web browser definitely support many ways of solving the problem, but it's not really part of the syntax of the language like (for example) an "if" statement is part of the syntax.
@Raynos It would be interesting to see a jsperf test between those :-)
0
<a href="#" class="clickie size-1" >Small text </a>
<a href="#" class="clickie size-2" >Medium text </a>
<a href="#" class="clickie size-3" >Large text </a>

You should change the markup not to rely on inline javascript.

// bind the event handler to all <a> tags
var as = document.getElementsByTagNames("a");
for (var i = 0, ii = as.length; i < ii; i++) {
    as[i].onclick = setText;
}

function setText(ev) {
    // get the em size from the class
    var size = /[.]*text-([\d][.]*)/.exec(ev.target.className)[1]
    var divs = document.querySelectorAll("div.buy_content");
    // set the style on all divs.
    for (var i = 0, ii = divs.length; i < ii; i++) {
        divs[i].style.fontSize = size + "em";
    }
}

There are issues with browser support (mainly IE7 and lower) so you need some more boilerplate to make it work.

Comments

0

You can't really do this (easily/readably/cleanly) with inline and stock JavaScript because the JavaScript DOM API doesn't provide a way to reference a CSS class since this isn't part of the DOM. You would have to populate an array or list with HTML elements that have that class applied to them and then iterate over the collection.

JQuery provides selectors and iterators to make this very simple, but if you can't use libraries then doing this inline isn't a good idea. Put it in a function in a script block or an external .js file.

EDIT:

A few people pointed out querySelectorAll, which will select by class but from what I have read isn't completely cross platform (doesn't work on IE below IE 8).

Further, to clarify on my original post, when I said that the DOM API doesn't allow you to access an element by class, what I meant was that it couldn't be done with DOM traversal. querySelectAll or the JQuery selectors perform DOM traversal with functions that inspect elements and their properties, retrieve the objects, and populate collections. Even getElementById performs attribute inspection. I suppose, in retrospect, it's a moot point, but since he wasn't using selectors or attribute queries in his original code I thought that he was asking if there was JS syntax that was as simple as what he was currently using. That's why I mentioned functions. In my head, even something like getElementById is a function since, well, it is a function.

23 Comments

Since when were classes not part of the DOM?
A class is an ATTRIBUTE of an element in the DOM. It is not part of the DOM itself.
Ever heard of querySelectorAll ? That's part of the DOM.
The Document Object Model is populated by elements. Elements have attributes that can be used to select objects in the DOM. A class is not part of the Document Object Model, it is an attribute of elements in the DOM tree that can be used as a selector. I'm referring to the DOM as a Model, not a Spec. I figured that specifying that would be redundant since the M stands for Model.
@DougStephen "the JavaScript DOM API" contains querySelectorAll
|
0

I believe what you are looking for is insertRule (this is exactly what you asked for... kinda):

document.styleSheets[document.styleSheets.length-1].insertRule('div.buy_content {font-size: 1em}',document.styleSheets[document.styleSheets.length-1].length)

document.styleSheets[document.styleSheets.length-1] is your last stylesheet. the new rule will go at index document.styleSheets[document.styleSheets.length].length

http://www.quirksmode.org/dom/w3c_css.html#t22

also... deleteRule:

http://www.quirksmode.org/dom/w3c_css.html#t21

BUT, a better way to go would be to getElementsByClassName, loop through em, check their nodeName for "DIV", then apply the styles the old fashioned way.

2 Comments

btw. IE hasn't supported most styleSheet functions until IE9.
not strictly true. It has proprietary named versions of the W3C standard that work in much the same way.
0

Leverage CSS to do the selection work for you:

body.smalltext  .buy_content { font-size: 1em; }
body.mediumtext .buy_content { font-size: 2em; }
body.largetext  .buy_content { font-size: 3em; }

...

<input type="button" value="Small text"  id="smalltext"/>
<input type="button" value="Medium text" id="mediumtext"/>
<input type="button" value="Large text"  id="largetext"/>

...

document.getElementById('smalltext').onclick= function() {
    document.body.className= 'smalltext';
};
document.getElementById('mediumtext').onclick= function() {
    document.body.className= 'mediumtext';
};
document.getElementById('largetext').onclick= function() {
    document.body.className= 'largetext';
};

Comments

0

My first suggestion to answer your exact question:

If your project is bigger in scope than just this one thing:

  1. Download jQuery
  2. Use code:

    $('div.buy_content')
    

    Which returns a jQuery array object of all the divs which you can further manipulate.

My second suggestion based on thinking more deeply about what you're trying to do:

Either completely replace the stylesheet in script or modify the existing stylesheet to change the style. Don't loop through all the DIVs in the document and change their style assignment, instead change the meaning of their already-assigned style.

2 Comments

jQuery isn't needed for just this.
No, but I bet you the OP's overall project needs something like it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.