Ways to change id attribute in html
Solution 1
From a purely JavaScript persepctive, the simplest and best way of changing the body's ID is
document.body.id = "collection";
However, you may be better off using a class to avoid any potential conflict of your ID with any other ID in the page. Giving the body an ID doesn't seem terribly useful given that there is only one <body>
element in the page and it can be referenced via document.body
in JavaScript and body
in CSS.
If you want to change an element in the page without reloading the whole page then JavaScript is your only option. If the change is vital to the functionality of your page, you should also provide a non-JavaScript fallback.
Solution 2
Should I use JavaScript?
Yes, based on the knowledge that you want this to happen during a click event. The most efficient way would be
document.body.id = "collection";
a less efficient way would be
document.getElementById("index").id = "collection";
Comments
-
thikonom almost 2 years
I'm building a website and I have an unsorted list with some list elements. When I click on some of these list items I want my
<body>
’s id to change fromid="index"
toid="collection"
.What's the most efficient way to do that?
- Should I use JavaScript?
- Should I put all the body code in a
{% block %}
and override it when I click on the special list items? - An other way?
-
Sparafusile over 13 yearsQuestion wasn't asked with the jQuery tag nor did the asker mention jQuery at all. THis is much easier to understand and implement without using jQuery.
-
chaos over 13 yearsjQuery is a subset of Javascript. The question is already schizophrenic, since it asks how to change the id "in HTML" and then is tagged with, and mentions Javascript.
-
Andy E over 13 years+1 - not sure who down voted but it seemed harsh. I also agree that giving the body an ID is rarely useful.
-
Ruan Mendes over 13 yearsAgree with Tim, changing the id seems wrong, you shouldn't need to change ids. Changing a class seems more like what you want in this case, specially if you're using it so that different CSS will apply
-
Joe Dargie over 13 yearsif we’re splitting hairs, jQuery is a framework written in JavaScript, rather than a subset of JavaScript. Calling it a subset implies that there are parts of JavaScript that you can’t use when you’re writing jQuery, and I don’t think that’s true.
-
chaos over 13 yearsSurely it is equally nonsensical to call jQuery out-of-bounds when Javascript is in-bounds.
-
Sparafusile over 13 yearsthat implies that using jQuery requires nothing in the term of learning a new library and syntax which isn't the case. Just because somebody knows JavaScript does not mean they can simply switch to jQuery on a whim.