Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass div to javascript function and change its style

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/

like image 628
ryantuck Avatar asked Sep 05 '25 17:09

ryantuck


2 Answers

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

like image 75
Sachin Avatar answered Sep 07 '25 09:09

Sachin


Change the script placement combo to no wrap - in <head> (second combo box on the left panel)

like image 21
Claudio Redi Avatar answered Sep 07 '25 09:09

Claudio Redi