Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .toggleId() add remove div id?

I have tried some solutions but nothing seems to work. I want to change the div id to one another (example: #red to #blue and then back to #red) just like .toggleClass(). I tried to toggle attribute but it didn't works.

I already used classes with !important tags to elements. So the only thing left is to use id's.

jsfiddle

HTML

<div id="red"></div>

CSS

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

JavaScript

$("#red").click(function () {
    $(this).attr("id", "#blue");
});
like image 869
Anonymous Avatar asked Jun 25 '26 04:06

Anonymous


1 Answers

You're almost there - but you don't need the # in the .attr statement. It should be:

$(this).attr("id", "blue");

In this fiddle I've done it for you (spoiler alert).

Or a bit shorter version here.

like image 91
kmoe Avatar answered Jun 27 '26 18:06

kmoe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!