Forum Moderators: open

Message Too Old, No Replies

Javascript Code to Overwrite Default Nested CSS

         

JRNeher

2:51 am on Aug 24, 2009 (gmt 0)

10+ Year Member



Hi all,
I have a page on my site that I am trying to figure out how to change the background image of a div tag using javascript depending on what value is entered upon entering the page. I know you can set something like: document.getElementById('id_name').style and so forth, but the layout I have is not making this possible. My div construction is as follows:

<div id="id_name1">
<div class="class_name">
...
</div>
</div>

I want to change the background image of 'class_name' in the above example, but ONLY in the 'id_name1' div. 'class_name' exists several other times throughout the page so I cannot just call the name of the class. Also, this page is constructed by an overall template that I can't (without a lot of work) rewrite.

My question is, with javascript, is it possible to call a nested class name that is in a particular id? Is it possible to do something like document.getElementById('id_name').class_name.style... or is there an equivalent way of doing this?

Thanks in advance for your time and help with this!

Fotiman

1:01 pm on Aug 24, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Many of the JavaScript frameworks provide methods for getting elements by class name. The Yahoo UI Library also includes a Selector Utility [developer.yahoo.com] that you could use like this:

<script src="http://yui.yahooapis.com/2.7.0/build/yahoo/yahoo-min.js"></script>
<script src="http://yui.yahooapis.com/2.7.0/build/selector/selector-min.js"></script>
<script type="text/javascript">
var node = YAHOO.util.Selector.query('div.class_name', 'id_name1', true);
// node now contains the element you want to change
</script>

And if you were looking to set style properties, the Yahoo UI Library also includes the Dom Utility [developer.yahoo.com], which includes cross-browser methods for setting styles or applying classes (among other things). YUI is well documented and easy to use.

Other libraries, like jQuery, also include methods for selecting elements by class name. The YUI method above is just one way to solve your challenge.