1

I have this form and several divs in it. The matter is, that color of one div is set with javascript, randomly, and border of another div has to be in one color with first one. It gets even more complicated, because several divs have one class names. Basically, what I mean here is that one house should be of one color, and "roof" depends on content, color of which is set randomly with js. worked on this for quite a long time, but seem to have no solution(

I guess, javascript should look something like this

document.getElementByClassName("roof").style.border-bottom-color = document.getElementByClassName("contents").style.background-color;

my jfiddle with html and css

cweiske
  • 30,033
  • 14
  • 133
  • 194
  • It's `getElementsByClassName`, with an s after "element". It returns an array and you need to iterate on it (or take the first element) – Jacopofar Jul 11 '13 at 12:54
  • 1
    also its borderBottomColor not border-bottom-color. The general rule is that when a property in CSS uses a - sign then in the JS its removed and the next word is capitalized. The same goes for background-color becomes backgroundColor – Pete D Jul 11 '13 at 12:59
  • can you use jquery ? because all browser does not support getElementsByClassName. – Sudarshan Tanwar Jul 11 '13 at 13:02
  • i would be gratefull for all working solutions for this problem. I do not know how to apply jquery here, I'm a newcomer in web programming. – chaartreuse Jul 11 '13 at 13:07

1 Answers1

1

If you'd like to keep "Pure" JS, take a look on this approach:

document.getElementsByClassName("roof")[0].style.borderBottomColor = 

getStyle(document.getElementsByClassName("contents")[0], 'backgroundColor');

function getStyle(el,styleProp)
{
    if (el.currentStyle)
        return el.currentStyle[styleProp];

    return document.defaultView.getComputedStyle(el,null)[styleProp];
}

Please notice, that getElementsByClassName returns a set of elements which have all the given class names. To access all of them and fill in elements border with ramdom color i can advice you to go in loop throuth them like:

var yourElements = document.getElementsByClassName('className');
for(var i=0; i<yourElements.length; i++) { 
  yourElements[i].style.borderColor= "#RANDOM_COLOR";
}

Advanced technique is to use jQuery, and correct answer was given above by JustAnil.

Hope it helps. Cheers!

Ignat B.
  • 665
  • 1
  • 10
  • 20
  • Good job. I was looking also how to do it in pure js but you beat me to it. +1 – Pete D Jul 11 '13 at 13:41
  • 1
    Here is a example of what he posted. I changed it a little and put the code for changing the color within the loop but it's what @Ignat B. used. http://jsfiddle.net/zaEnZ/38/ – Pete D Jul 11 '13 at 13:51
  • Cheers @Pete D, this question was a challenge for me as well. Thanks for your update! – Ignat B. Jul 11 '13 at 13:59
  • Thank you! I never imagined to find someone from Ukraine here) – chaartreuse Jul 12 '13 at 13:38