I am trying to change div color on click but it is not working:
<html>
<head>
<script>
function data(){
var MyDiv1 = document.getElementById('newdata').innerHTML;
alert(MyDiv1)
if(MyDiv1==1) {
document.getElementsById('newdata').style.backgroundColor = "green";
}
}
</script>
</head>
<body >
<div id="newdata" style="background-color: red; width: 100px;height: 50px;">
1
</div>
<a href="#" onclick="data();">Logout</a>
</body>
</html>
Where am I wrong here?
Any help will be appreciated
<html>
<head>
</head>
<body >
<div id="newdata" style="background-color: red; width: 100px;height: 50px;">
1
</div>
<a href="#" onclick="data();">Logout</a>
</body>
</html>
<script>
function data(){
document.getElementById('newdata').style.backgroundColor = "green";
}
</script>
1) Script at the end;
2) Element not Elements
3) Call the right div name
4) That alert and if don't have a purpose
it should be newdata
document.getElementById('newdata').style.backgroundColor = "green";
so your function will be
function data(){
var MyDiv1 = document.getElementById('newdata').innerHTML;
alert(MyDiv1)
if(MyDiv1==1) {
document.getElementById('newdata').style.backgroundColor = "green";
}
}
There were a couple of problems with your attempt. The following snippet does what you want:
function data(){ var myDiv = document.getElementById('newdata'); var content = myDiv.innerHTML; if (content.trim() === "1") { myDiv.style.backgroundColor = "green"; } }
<div id="newdata" style="background-color: red; width: 100px;height: 50px;"> 1 </div> <a href="#" onclick="data();">Logout</a>
<div>
element and its contents.
I have put the two into separate variables.
I have used .trim()
to remove any leading and trailing spaces from the contents of the <div>
and also used the strict comparison ===
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.