How can I change the id in javascript?

Discussion in 'Web Design' started by benjamin.morgan, Jul 7, 2012.

to remove all ads.
  1. benjamin.morgan

    benjamin.morgan New Member

    Messages:
    269
    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;
    ​
     
  2. ronaldroe

    ronaldroe Super Moderator Staff Member

    Messages:
    1,223
    Forked ya. I used jQuery's .attr() function to change the ID when you click the button. You could also use .toggle() instead of .click(), and add a second function to turn back to red when it's clicked again.
     
    Last edited: Jul 7, 2012
  3. benjamin.morgan

    benjamin.morgan New Member

    Messages:
    269
    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?
     
  4. benjamin.morgan

    benjamin.morgan New Member

    Messages:
    269
    If I used jQuery I could just use classes. Why doesn't red.id = "blue" change the id?
     
  5. chrishirst

    chrishirst Well-Known Member Staff Member

    Messages:
    2,662
    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.
     
  6. benjamin.morgan

    benjamin.morgan New Member

    Messages:
    269
  7. chrishirst

    chrishirst Well-Known Member Staff Member

    Messages:
    2,662
    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.
     
  8. benjamin.morgan

    benjamin.morgan New Member

    Messages:
    269
    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.
     
  9. ronaldroe

    ronaldroe Super Moderator Staff Member

    Messages:
    1,223
    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.
     
  10. benjamin.morgan

    benjamin.morgan New Member

    Messages:
    269
    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.
     
  11. CaldwellYSR

    CaldwellYSR Member

    Messages:
    658
    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...
     
  12. benjamin.morgan

    benjamin.morgan New Member

    Messages:
    269
    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.
     
  13. CaldwellYSR

    CaldwellYSR Member

    Messages:
    658
    That code looks good to me, should work fine.
     
  14. chrishirst

    chrishirst Well-Known Member Staff Member

    Messages:
    2,662
    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.
     
  15. CaldwellYSR

    CaldwellYSR Member

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

    chrishirst Well-Known Member Staff Member

    Messages:
    2,662
    I thought that also.

    However, this post;
    suggests otherwise.
     
  17. benjamin.morgan

    benjamin.morgan New Member

    Messages:
    269
    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: Jul 9, 2012
  18. amelia-t

    amelia-t New Member

    Messages:
    6
  19. CaldwellYSR

    CaldwellYSR Member

    Messages:
    658
    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: Jul 9, 2012
  20. benjamin.morgan

    benjamin.morgan New Member

    Messages:
    269
    I will be sure to remember that. Thanks for you help.
     

Share This Page