-3

I want to show the p element with id=ex2 red if the color of p element with id=ex1 is red. I have tried but failed. Please help.

<p id="ex1" style="color: red;">red</p>
<p id="ex2">f</p>
<script type="text/javascript">
    var myElement = document.getElementById('ex1');
    if (myElement.style.color = red){
        document.getElementById('ex2').innerHTML = 'red';
    }
</script>
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • 2
    Watch your `if` condition! `=` is the [assignment operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators), `==` is the [comparison operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators). They are different things with different effects. `red` is a variable, you probably want the [string literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) `'red'`. – axiac Feb 08 '18 at 14:36
  • `console.log(myElement.style.color)` and `red` is not defined anywhere. – epascarello Feb 08 '18 at 14:37

1 Answers1

1

You have some typos in your code. To set the color property you have to use style.color on the element like you did to get the color. But you are using innerHTML which is used to set or return the HTML content (inner HTML) of an element. Try the following:

var myElement = document.getElementById('ex1');
var color = myElement.style.color;
if ( color == 'red'){
    document.getElementById('ex2').style.color = 'red';
}
<p id="ex1" style="color: red;">red</p>
<p id="ex2">f</p>
Mamun
  • 66,969
  • 9
  • 47
  • 59