0

There is the following HTML code:

<body>
  <menu>
  </menu>
  ... other html
</body>

I need to replace <menu> tag with HTML content from variable. I know how I can change innerHTML using string variable with content (variable 'template');

menu.innerHTML = template;

Variable 'template' contains '<ul class="menu"></ul>'. As result I want to have the following HTML:

<body>
  <ul class="menu">
  </ul>
  ... other html
</body>
3
  • using native JS no jQuery? Commented Mar 7, 2016 at 10:17
  • 2
    Since you know about innerHTML, you may be interested to know there's a corresponding outerHTML. Commented Mar 7, 2016 at 10:19
  • 1
    @JamesThorpe That (plus a little example) should probably an answer, and not a comment. Commented Mar 7, 2016 at 10:21

4 Answers 4

2

You mention innerHTML; there's a corresponding outerHTML property that, when set, will replace the element and all children with your update:

var menu = document.getElementsByTagName('menu')[0];
menu.outerHTML = template;
Sign up to request clarification or add additional context in comments.

Comments

1

Try:

var body = document.getElementsByTagName('body')[0];
body.innerHTML = body.innerHTML.replace(/<menu>[\s\S]*?<\/menu>/, template);

Comments

0

Try this

var str = '<ul class="menu"></ul>';
var menu = document.getElementsByName('menu');
var parentMenu = menu.parentNode;
parentMenu.removeChild(menu);
parentMenu.innerHTML = str + parentMenu.innerHTML;

Comments

0

try this

var elem = document.getElementsByTagName('body')[0]; // Select any element you want.
var target = elem.innerHTML;
elem.innerHTML = target.replace(/(<menu)/igm, '<ul class="menu"').replace(/<\/menu>/igm, '</ul>');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.