Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've got a little problem with my JavaScript. I'm trying to learn how to change the attribute on a page using setAttribute(name, value), and nothing happens.

This is my test site's HTML code:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8" />
<title>Test</title>
</head>

<body>
<div id="test" class="time"></div>
<script src="js/script.js"></script>
</body>
</html>

This is my JavaScript code:

if(document.getElementById("test").hasAttribute("class")) {
    alert("got message");
    var test = "test";
    document.getElementById("test").setAttribute("class", test);
}

It's very simple, so it should work, but only an alert pops up, and when I check the source of page, nothing changes. To be honest - I tried several different approaches and nothing worked. It must be something really, really stupid but I can't find it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
214 views
Welcome To Ask or Share your Answers For Others

1 Answer

Change all classes

document.getElementById("test").className = test;

Add classes:

document.getElementById("test").className += test;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...