Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
43
rated 0 times [  49] [ 6]  / answers: 1 / hits: 24708  / 11 Years ago, thu, october 17, 2013, 12:00:00

I'm trying to pass a div's id to a javascript function that does something simple, like change the background color of the div.



Weird thing is, my code works in the w3schools.com Tryit editor, but not in JSFiddle. It also doesn't work in my compiler (Coda 2).



Is this even the right way of going about this? Here's my code:



<!DOCTYPE html>
<html>
<head>
<script>
function changeBackgroundColor(asdf)
{
asdf.style.backgroundColor = #fff000;
}
</script>
</head>
<body>

<div id=myDiv style=background:red> this is my div </div>
<button onclick=changeBackgroundColor(myDiv)> Set background color </button>

</body>
</html>


and here's the JSFiddle stuff: http://jsfiddle.net/BH9Rs/


More From » html

 Answers
14

You need to use document.getElementById to get the element from the id



function changeBackgroundColor(asdf){
document.getElementById(asdf).style.backgroundColor = #fff000;
}


and pass the id like this (in single quotes)



<button onclick=changeBackgroundColor('myDiv')> 


And in your fiddle put your function inside the Head section.
(select no-wrap in Head) at left side Framework and Extension option



Js Fiddle Demo


[#74914] Wednesday, October 16, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
luzv

Total Points: 178
Total Questions: 105
Total Answers: 114

Location: Palau
Member since Tue, May 30, 2023
1 Year ago
;