How can I change the id in javascript?

benjamin.morgan

New Member
Why doesn't this work? I have the code in a JSFIDDLE if you want to run it at http://jsfiddle.net/ZTGL7/2/

HTML
Code:
<div id="red"></div>
<input type="button" id="clickme" value="Click Here">​

CSS
Code:
#red {
    background: red;
    height: 100px;
    width: 100px;
}
#blue {
    background: blue;
    height: 100px;
    width: 100px;
}​

Javascript
Code:
function change() {
    var red = document.getElementById('red');
    red.id = "blue";
}

function init() {
   var clickme = document.getElementById('clickme');
   clickme.onclick = change;

}

window.onload = init;
​
 

benjamin.morgan

New Member
Hmm, Well I'm not using jQuery, I need a way to do this with regular Javascript. Also when I click the thing it adds 2 blue squares instead of one?
 

chrishirst

Well-Known Member
Staff member
If you change the ID of an element using javascript when you are referencing that element using getElementById() it loses the reference to the object thus cannot change it!

It's a bit like sitting on a tree branch and sawing through the branch nearer to the tree trunk than you are.
 

chrishirst

Well-Known Member
Staff member
That code would only change the first instance of the div elements in the document.

First of all you probably need to understand that javascript does NOT work using the document source code, it changes the memory image of the document, the Document Object Model. So as soon as the ID is changed the element no longer exists in the DOM.

Now if all you want to do is change a colour why not the class name or the elements style properties.
 

benjamin.morgan

New Member
Well, I am just using that as an example. I am trying to write a blackjack game without looking at other peoples code. I have a hit button but if it is pressed once it needs to change the id to hit2 so I can call a function by adding document.getElementById('hit2').onclick = hit2; and I would be able to do that with hit 1 but I can't do it with hit 2. I was trying not to use jQuery but it looks it would be easier if I do.
 

ronaldroe

Super Moderator
Staff member
You can still do what you're wanting to do using a class instead of an ID. It seems like you're going with the ID because it's used only once on the page. The "ID if it's used once, class if used more than once" isn't really a rule. Not for CSS anyway. ID's used only once on a page is an HTML rule, not CSS. IDs exist for targeting purposes, but have been added as stylable in CSS. Classes, on the other hand can be used any number of times, including only once, and it's perfectly valid.
 

benjamin.morgan

New Member
I know that but without jQuery how can I add and remove classes as needed? That is what I love about jQuery because it is easy. Maybe I can find the code to put in a function and use that. Currently if I use jQuery for my blackjack game it will be just to remove and add classes as the main reason.
 

CaldwellYSR

Member
I know that but without jQuery how can I add and remove classes as needed? That is what I love about jQuery because it is easy. Maybe I can find the code to put in a function and use that. Currently if I use jQuery for my blackjack game it will be just to remove and add classes as the main reason.

You can add a class by saying
Code:
document.getElementById("red").className += "blue";

removing classes can probably be done with the replace function

Code:
document.getElementById("red").className = document.getElementById("red").className.replace("blue","");

but I haven't actually tried that second snippet to see if it works or not...
 

benjamin.morgan

New Member
How would I see what class would call a function? Would I have to use an if statement and have something like this?
Code:
    if (document.getElementById('red').className === "blue") {
        function classIsBlue() {
                //code here
        }
    } else if() {
        etc.
    }

I definitely think you guys have helped me understand the DOM a little bit more and Matthew it seems like you are always helping me find an answer. That code worked beautifully for changing the class. I am going to try to get a working version in jQuery and then rewrite it without the jQuery library so I can see when I need classNames etc.

Thanks to everyone that helped me.
 

CaldwellYSR

Member
How would I see what class would call a function? Would I have to use an if statement and have something like this?
Code:
    if (document.getElementById('red').className === "blue") {
        function classIsBlue() {
                //code here
        }
    } else if() {
        etc.
    }

I definitely think you guys have helped me understand the DOM a little bit more and Matthew it seems like you are always helping me find an answer. That code worked beautifully for changing the class. I am going to try to get a working version in jQuery and then rewrite it without the jQuery library so I can see when I need classNames etc.

Thanks to everyone that helped me.

That code looks good to me, should work fine.
 

chrishirst

Well-Known Member
Staff member
I know that but without jQuery how can I add and remove classes as needed?
How do you think we managed to do all these thing before jQuery or mooTools frameworks came along?

What you should do is get out of the habit of using "frameworks" for everything, because one day you will have a project where they are NOT available to you. Learning how to use DOM scripting and DOM node referencing instead will make you a better developer simply because you are not limited to the "framework" nor do you need to have the framework overhead when you only need to use ONE function from it.

The ability to write all your own functions also means that you can develop your own function libraries that you can "mix and match" as you need to, which means the end of framework "conflicts" and the inevitable "Why doesn't it work" headscratching.
 

CaldwellYSR

Member
How do you think we managed to do all these thing before jQuery or mooTools frameworks came along?

What you should do is get out of the habit of using "frameworks" for everything, because one day you will have a project where they are NOT available to you. Learning how to use DOM scripting and DOM node referencing instead will make you a better developer simply because you are not limited to the "framework" nor do you need to have the framework overhead when you only need to use ONE function from it.

The ability to write all your own functions also means that you can develop your own function libraries that you can "mix and match" as you need to, which means the end of framework "conflicts" and the inevitable "Why doesn't it work" headscratching.

I'm 99.999999% sure that's what he's trying to do here... he's trying to avoid jquery and learn core js.
 

chrishirst

Well-Known Member
Staff member
I thought that also.

However, this post;
I know that but without jQuery how can I add and remove classes as needed? That is what I love about jQuery because it is easy. Maybe I can find the code to put in a function and use that. Currently if I use jQuery for my blackjack game it will be just to remove and add classes as the main reason.
suggests otherwise.
 

benjamin.morgan

New Member
I got stuck with blackjack in jQuery too. Producing buggy results on some deals. :(. I don't know what is happening. Also, I just meant the add/remove class thing. I am trying to learn core js a lot more then go further into jQuery. I do have a question though since I am going to write this in jQuery first. How do you call a function. I am doing something like
Code:
	$('.stay').click(function() {
	//code here
        });
	$('.deal').click(function() {
	if (something) {
/* I want to call a function here. 
but I don't know how to call the stay.click function
 without rewriting the code inside this function..*/
       }
      });
 
Last edited:

CaldwellYSR

Member
I got stuck with blackjack in jQuery too. Producing buggy results on some deals. :(. I don't know what is happening. Also, I just meant the add/remove class thing. I am trying to learn core js a lot more then go further into jQuery. I do have a question though since I am going to write this in jQuery first. How do you call a function. I am doing something like
Code:
	$('.stay').click(function() {
	//code here
        });
	$('.deal').click(function() {
	if (something) {
/* I want to call a function here. 
but I don't know how to call the stay.click function
 without rewriting the code inside this function..*/
       }
      });

What I would do is set up a function for what you want to happen in stay.click then you can call that function in both situations. For instance...

Code:
function stayClick() {
    alert("Woo hoo it was clicked");
}
$('.stay').click(stayClick()); /* I can't remember if you need the parens or not */
$('.deal').click(function() {
    // Whatever you want to happen
    stayClick();                   
});
 
Last edited:
Top