user765084
user765084

Reputation: 1

Need Javascript syntax to reference a CSS class instead of HTML element

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>

Upvotes: 0

Views: 5000

Answers (6)

ErikE
ErikE

Reputation: 50201

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.

Upvotes: 0

bobince
bobince

Reputation: 536339

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';
};

Upvotes: 0

MicronXD
MicronXD

Reputation: 2220

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.

Upvotes: 0

Doug Stephen
Doug Stephen

Reputation: 7351

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.

Upvotes: 0

Raynos
Raynos

Reputation: 169383

<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.

Upvotes: 0

Pointy
Pointy

Reputation: 413702

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.

Upvotes: 3

Related Questions