4

I am a beginner in javascript. As mentioned in stack overflow query, I can remove or create elements within the DOM. However, can I replace the root element through javascript e.g. if I want to change an attribute of the HTML element through javascript?

Community
  • 1
  • 1
doon
  • 2,311
  • 7
  • 31
  • 52
  • 2
    Why would you need to replace the root element if you just want to change its attributes? – Barmar Apr 13 '15 at 03:53
  • The title of this question should be changed since OP is asking changing attribute. – jave.web Aug 02 '23 at 09:46
  • To actually change the root element (e.g. replace the whole document) you can use `document.documentElement.replaceWith(newHTML);` - this is a very rare edge case, usually you just want to change attributes of the existing one. – jave.web Aug 02 '23 at 09:50

1 Answers1

4

I think you're asking if you can modify the element, and the answer is yes.

var html = document.getElementsByTagName('html')[0];
html.title = "Foo"; // Set an attr on the element
sesamechicken
  • 1,928
  • 14
  • 19
  • 4
    You can just reference `document.documentElement`. No need to `getElementsByTagName()` – jfriend00 Apr 13 '15 at 04:31
  • True enough, I just wanted to provide a working example if the OP wanted to traverse further down the DOM and programmatically adjust other tags, like meta, for example. – sesamechicken Apr 13 '15 at 12:16