Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I agree with RobG that using classes is much better suited - especially if you ever decide to use a framework. In the off-case you don't want to here are some other ways:</p> <p><strong>Updated for Computed Styles</strong> - leaving the commented version at the bottom of post: The main difference in this one is that it gets the background image of the inline-style or the computed version (if its being set by a class for example).</p> <p>For getting computed styles, take a look at quirksmode.org. In particlar the bottom of the <a href="http://www.quirksmode.org/dom/getstyles.html" rel="nofollow">getstyles page</a>.</p> <p>Here is a <a href="http://jsfiddle.net/dWM8s/2/" rel="nofollow">fiddle</a> that is not working in jsfiddle (bit tired but I think it has to do with me using IE6 at work...), but works fine if you do it locally in a normal setting.</p> <pre><code>function add(x) { var parent = x.parentNode; var y = parent.currentStyle['backgroundImage'] || document.defaultView.getComputedStyle(parent,null).getPropertyValue('backgroundImage'); switch(true) { case (y.indexOf("1.png")!=-1): parent.style.backgroundImage = 'url("http://www.wskidmore.com/2.png")'; break; case (y.indexOf("2.png")!=-1): parent.style.backgroundImage = 'url("http://www.wskidmore.com/3.png")'; break; case (y.indexOf("3.png")!=-1): parent.style.backgroundImage = 'url("http://www.wskidmore.com/1.png")'; break; } } </code></pre> <p>Outdated, but commented with logic.</p> <pre><code>function add(x) { var y = x.parentNode.style.backgroundImage; // using indexOf will avoid the possible quote issue and possibly other odd browser quirks // switch true means it will do the first case it finds that evaluates to true switch(true) { // indexof means it looks through your string for the given substring // and returns the position so, "abc".indexOf("b") returns 1 (its 0 based) // if it doesnt find it anywhere it returns -1 // so for our switch, it looks inside the backgroundImage string // url("../assets/x.png") no-repeat 50% 50% // or whatever it may be for the part "1.png" // if it finds it, it will return 5, or 8, or whatever the position is // if not it returns -1 // so when this gets evaluated we check for "not -1" case (y.indexOf("1.png")!=-1): // if this case is true, then everything between the : and break; // will be performed, then it exits the switch y = 'url("../assets/2.png")'; break; case (y.indexOf("2.png")!=-1): y = 'url("../assets/3.png")'; break; case (y.indexOf("3.png")!=-1): y = 'url("../assets/4.png")'; break; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload