Reputation: 4267
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 from id="index"
to id="collection"
.
What's the most efficient way to do that?
{% block %}
and override it when I click on the special list items?Upvotes: 4
Views: 14881
Reputation: 324567
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.
Upvotes: 7
Reputation: 344565
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";
Upvotes: 1
Reputation: 124297
I would do it using jQuery, with the line $('#index').attr('id', 'collection');
.
Upvotes: 0
Reputation: 98796
Depends what you mean by “efficient”. Using JavaScript means the id
gets changed without another HTTP request being made to your server, so the user doesn’t have to wait for the page to reload.
However, if they revisit or reload the page after clicking on one of these list items, the list will go back to the way it was when the page was loaded. That might not be optimal for your context.
Upvotes: 0