How to compare a string in javascript to add a style?

0

I'm trying to compare an if else to add a style (border), as you see in my next code add an id to an element to apply the style, the style that works is the style that you add by default, if not Nothing is satisfied in the if and else (in case there is an error or something similar).

   	var myElement = document.getElementById("demo");



 if (myElement == 'company') {

 	 myElement.style.border = '2px solid red'; 
 }

 else {
	myElement.style.border = "2px solid blue";
}

//este es el estilo por default
 myElement.style.border = "2px solid green";
<!DOCTYPE html>
<html>
<head>
	<title>Example CSS3</title>
	<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>


<p id="demo">company</p>


<script src="script.js"></script>

</body>
</html>
    
asked by Gilberto 12.12.2017 в 21:38
source

1 answer

1

You are selecting the element but you need to select its content (You can do this with innerText or innerHTML ), in addition to the default style you should add it in your CSS since when you add it to the end of your JS will always be executed last, so the result of the condition will not be reflected:

var myElement = document.getElementById("demo");

if (myElement.innerText == 'company') {
 	 myElement.style.border = '2px solid red'; 
}else {
	myElement.style.border = "2px solid blue";
}
#demo{
  border: 2px solid green;
}
<!DOCTYPE html>
<html>
<head>
	<title>Example CSS3</title>
	<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>


<p id="demo">company</p>


<script src="script.js"></script>

</body>
</html>
    
answered by 12.12.2017 / 21:41
source