0

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.

3
  • Try document.getElementById("test").className = test. Commented Oct 7, 2013 at 16:30
  • Vanilla js attribute methods: setAttribute, getAttribute & removeAttribute Commented Oct 7, 2013 at 16:31
  • Contrary to what the text of the question says, the code uses attr() (which is undefined), not setAttribute(). When this part is fixed, the code works. Whatever might be happening, there is no information that could be used to track down the causes. Please delete this and post a new question when you have demonstrateable problem. Commented Oct 7, 2013 at 17:10

4 Answers 4

1

Change all classes

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

Add classes:

document.getElementById("test").className += test;
Sign up to request clarification or add additional context in comments.

4 Comments

So after changing document.getElementById("test").setAttribute("class", test); for document.getElementById("test").className = test; something should happen? Beacuse nothing changes. To be sure that we all are on that same page: after writing script and saving it to js/script.js everything i need to do is open index.html, close pop-up and class name in souce code (rmb on document -> show source) should be different? If that's the plan - still nothing.
You need to add a space in front of the value you are concatenating: .className += " "+test;
that or just set the test variable to include the space already, var test = ' myClass';
@Speedy I believe my suggestion is a more scalable and maintainable way to do it
0

This is how I helped me when I started with JS and did not like to use JQuery.

    function hasClass(element,class){
    if(element==null){
        return false;
    }
    ret = false;
    var classes = element.className.split(" ");
    for(var i=0;i<classes.length;i++){
        if(classes[i]==class){ret = true;}
    }
    return ret;
}
function removeClass(element,class){
    if(hasClass(element,class)){
        if(element.className==class){
            element.className = "";
        }else{
            var classes = element.className.split(" ");
            element.className = "";
            var unset = false;
            for(var i=0;i<classes.length;i++){
                if(classes[i]!=class){
                    if(unset && element.className==""){
                        element.className = classes[i];
                        unset = true;
                    }
                    element.className+=" "+classes[i];
                }
            }
        }
    }
}
function addClass(element,class){
    if(!hasClass(element,class)){
        if(element.className!=""){
            element.className += " "+class;
        }else{
            element.className = class;
        }
    }
}
function getElementsByClassName(tag,class){
    var ret = new Array();
    var elements = document.getElementsByTagName(tag);
    for(var i = 0;i<elements.length;i++){
        var element = elements[i];
        var classes = element.className.split(" ");
        for(var k = 0; k<classes.length;k++){
            if(classes[k]==class){ret[(ret.length)]=elements[i];}
        }
    }
    return ret;
}

Comments

0

What you say you're doing:

I'm trying to learn how to change attribute on page using setAttribute(name, value) and nothing happens.

What you're actually doing:

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

document.getElementById("test").attr("class", test);

}

You need to change .attr(..) to .setAttribute(..)

Also, be aware that setAttribute will overwrite instead of concatentate the value of the attribute you specify.

1 Comment

yeah, i know - wrong code sample. Anyway attr(something, something) or setAttribute(name, value) make no difference - none of them work. Acctualy - i try every sample of code that you guys posted and no effect. So something is realy, realy wierd with my computer or I just suck in JS.
0

You can just use the .className property of DOM objects to access the class attribute.

You can replace your code with this:

// if the class name is not empty, then change it
if (document.getElementById("test").className) {
    alert("got message");
    document.getElementById("test").className = "test";
}

Working demo: http://jsfiddle.net/jfriend00/x25Lj/

P.S. There is no .attr() method on DOM objects. You may have seen that used with jQuery objects which you do not have here.

5 Comments

yeah, i know - i accidentaly pasted one of many versions of code that i tried. None of them worked. And no, code that you show also doesn't work - i pasted it, no changes and no effect. I'm realy confused.
@user2855304 - there's something else going on with your page because my code works just fine here: jsfiddle.net/jfriend00/x25Lj
@user2855304 - you should check your browser's error console. You may have a problem with your external script being loaded or an error in it that stops javascript execution.
Yeah, i must check it but problem shows on three different browsers. Anyway - thank's for help.
@user2855304 - the problem is likely in your HTML page, so of course it would happen in multiple browsers. Check the error console in your browser and it will probably show you what the problem is in your web page. This is one of the first things you must learn in javascript development. Always check for errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.