开发者

Ways to change id attribute in html

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?

  1. Should I use JavaScript?
  2. Should I put all the body code in a {% block %} and override it when I click on the special list items?
  3. An other way?


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.


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";


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.


I would do it using jQuery, with the line $('#index').attr('id', 'collection');.


document.getElementById( "index" ).id = "collection";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜