Joris
Joris

Reputation: 53

javascript innerhtml shows as text

I'm pretty new to javascript. And i'm trying to add a div at the top of my <body>. But for some reason it adds my code as text like this

enter image description here

this is my code at the moment.

function addDark() {
  document.body.prepend("<div style='position:fixed;top:0;left:0;z-index:999;background:black;opacity:.9;'></div>")
}

How can i fix this problem? Thanks in advance, Joris

Upvotes: 0

Views: 73

Answers (3)

Joris
Joris

Reputation: 53

I fixed it by adding it like this, and not with ".innerhtml" Thanks for all the help!

  var div = document.createElement('div');
  div.className = "name";
  div.style.position = "fixed";
  div.style.zIndex = "999";
  document.body.prepend(div);

Upvotes: 1

Daedalus
Daedalus

Reputation: 7722

Depending on what browsers you are aiming to have your website support, there are a few ways.

  1. The first mentioned way, by me in a comment to your question, is to of course create the div element manually, and append that:

    var div = document.createElement('div');
    div.style.position = 'fixed';
    div.style.top = 0;
    div.innerText = 'more text';
    document.body.prepend(div);
    

    Of course, the above way would take awhile to type out, and is thus not really fun. Here is the documentation link for Node.innerText.

  2. Then there's Element.innerHTML, mentioned by Vivek. This method isn't preferrable, as it wipes the document body to insert the element.. which unless you're listening to events for in a very specific way, wipes those as well. I'm not going to get into that way as it is out of scope for this answer.

  3. Finally, there is another way; Element.querySelector(). You can use this method to parse the HTML you write as a string, before inserting in the desired position. Please refer to the support chart at the bottom of the linked documentation to see if it is supported in your targetted browsers:

    var span = document.createElement('span');
    span.innerHTML = "<div style='position:fixed;top:0;left:0;z-index:999;background:black;opacity:.9;color:white;'>more text</div>";
    var div = span.querySelector('div');
    document.body.prepend(div);
    

Demo of #3:

var span = document.createElement('span');
span.innerHTML = "<div style='position:fixed;top:0;left:0;z-index:999;background:black;opacity:.9;color:white;'>more text</div>";
var div = span.querySelector('div');
document.body.prepend(div);

Upvotes: 1

Pierre Capo
Pierre Capo

Reputation: 1053

You need to create an html element being a div. Then you can append your div inside the body element.

function addDark() {
    var div = document.createElement("div");
    // tweak your css for the div here                           
    document.body.prepend(div);
} 

Upvotes: 1

Related Questions