Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why doesn't this document.innerHTML function work?

I am not sure why if you trigger the function, nothing happens

loginButton.addEventListener("click", function() {
  const password = document.getElementById("password").value;

  if (password === "password") {
    alert("Correct!");
    document.innerHTML = <embed src="http://stackoverflow.com" style="width:500px; height: 700px;"></embed>;
  } else {
    loginMessage.textContent = "Invalid password.";
  }
});

I was expecting a embed of a website

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There are at least four separate reasons your code doesn’t work.

document doesn’t support innerHTML

innerHTML is a property found on HTML elements. The document object is not an HTML element.

Consider document.body.innerHTML instead.

innerHTML expects a string

As pointed out by Mina, <embed src="http://stackoverflow.com" style="width:500px; height: 700px;"></embed> is a syntax error in JavaScript.

You should see this error reported in the Console of your browser’s developer tools.

You need to assign a string to innerHTML. Wrap the code in ' (or " and escape the " in the data).

= '<embed src="http://stackoverflow.com" style="width:500px; height: 700px;"></embed>';

<embed> isn’t for HTML documents

Also note that according to MDN:

Keep in mind that most modern browsers have deprecated and removed support for browser plug-ins, so relying upon <embed> is generally not wise if you want your site to be operable on the average user’s browser.

Consider <iframe> instead.

Stackoverflow forbids it

Stackoverflow has a CSP that forbids other sites from embedding it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading