I am trying to change the CSS of one element on click of another element. I've searched a lot but nothing works perfectly. Currently I am using the below code, but it doesn't work. Can anyone tell me what I missed?
<div id="foo">hello world!</div> <img src="zoom.png" onclick="myFunction()" />
function myFunction() { document.getElementById('foo').style.cssText = 'background-color: red; color: white; font-size: 44px'; }
If you want to change the CSS styles dynamically you'll have to attach this portion of code to some event. For example, if you want to change the styles of your element when clicking on a button, then you have to first listen to the click event and attach a function containing the previous code.
Change CSS Property With getElementById in JavaScriptIf we have a unique id assigned to an HTML element, we can query it and change its style with the getElementById() function of the Document interface. It is the most widely used method by web developers.
Firstly, using on*
attributes to add event handlers is a very outdated way of achieving what you want. As you've tagged your question with jQuery, here's a jQuery implementation:
<div id="foo">hello world!</div> <img src="zoom.png" id="image" />
$('#image').click(function() { $('#foo').css({ 'background-color': 'red', 'color': 'white', 'font-size': '44px' }); });
A more efficient method is to put those styles into a class, and then add that class onclick, like this:
$('#image').click(function() { $('#foo').addClass('myClass'); });
.myClass { background-color: red; color: white; font-size: 44px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div id="foo">hello world!</div> <img src="https://i.imgur.com/9zbkKVz.png?1" id="image" />
Here's a plain Javascript implementation of the above for those who require it:
document.querySelector('#image').addEventListener('click', () => { document.querySelector('#foo').classList.add('myClass'); });
.myClass { background-color: red; color: white; font-size: 44px; }
<div id="foo">hello world!</div> <img src="https://i.imgur.com/9zbkKVz.png?1" id="image" />
Try this:
CSS
.style1{ background-color:red; color:white; font-size:44px; }
HTML
<div id="foo">hello world!</div> <img src="zoom.png" onclick="myFunction()" />
Javascript
function myFunction() { document.getElementById('foo').setAttribute("class", "style1"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With