Change text color with javascript?

I want to change the title color when a button is clicked. This is my code, but it does not work, and I cannot understand why not ...

<div id="about">About Snakelane</div> <input type="image" src="http://www.blakechris.com/snakelane/assets/about.png" onclick="init()" id="btn"> 

and my js ...

 var about; function init() { about = document.getElementById("about").innerHTML; about.style.color = 'blue'; } 

Thanks in advance!

+8
source share
5 answers

You set the style for each element, not its contents:

 function init() { document.getElementById("about").style.color = 'blue'; } 

With innerHTML you get / set the content of the element. Therefore, if you want to change your title, innerHTML is the way to go.

In your case, however, you just want to change the property of the element (change the color of the text inside it), so you are addressing the style property of the element itself.

+16
source

use ONLY

 function init() { about = document.getElementById("about"); about.style.color = 'blue'; } 

.innerHTML() sets or gets the HTML syntax that describes the descendants of an element. All you need is an object here.

Demo

+2
source

Try entering the code:

 $(document).ready(function(){ $('#about').css({'background-color':'black'}); }); 

http://jsfiddle.net/jPCFC/

+1
source

innerHTML is a string representing the contents of an element.

You want to change the element itself. Drop the .innerHTML part.

0
source
 <div id="about">About Snakelane</div> <input type="image" src="http://www.blakechris.com/snakelane/assets/about.png" onclick="init()" id="btn"> <script> var about; function init() { about = document.getElementById("about"); about.style.color = 'blue'; } 

0
source

Source: https://habr.com/ru/post/1494062/


All Articles