1

I have a button in a webpage that is linked to a Javascript function, which creates a div as follows:

function creatediv(){
   var div = document.createElement('div');
   div.innerHTML = document.getElementById('innerhtmlbox').value;
   document.body.appendChild(div);
}

However, it is not working. Can anyone give me any advice?

6
  • what is document.getElementById('innerhtml').value Commented Oct 15, 2015 at 17:32
  • First I'd just put alert("hey"); to make sure your button click is actually being registered... Commented Oct 15, 2015 at 17:33
  • 1
    Works perfectly fine for me -> jsfiddle.net/t4c5yq24 Commented Oct 15, 2015 at 17:34
  • is document.getElementById('innerhtml') a form element? if not, the result of value seems doubtful to me. Commented Oct 15, 2015 at 17:35
  • 2
    Protip: for the sake of readability don't name your element after a DOM attribute. It can get confusing. Commented Oct 15, 2015 at 17:35

2 Answers 2

5

Try this:

function createDiv() {
  let div = document.createElement('div');
  div.innerText = document.getElementById('getText').innerText;
  document.body.appendChild(div);
}
<button onClick="createDiv()">Click me!</button>

<div id="getText" style="display: none;">
  INNER TEXT
</div>

Sign up to request clarification or add additional context in comments.

3 Comments

So what you're saying is that the function works, or did you actually change anything? Maybe an explanation!
This works. I may be wrong here, but I believe the .value function is to return the content of text fields, as in inputs, that's why I believe the code that OP was trying to execute didnt work
But how do you know the OP isn't using an input to get the HTML that is to be used in the newly created element ?
0

You need to use innerText

function creatediv() {
    var div = document.createElement('div');
    div.innerHTML = document.getElementById('innerhtml').textContent;
    document.body.appendChild(div);
}
creatediv();

http://jsfiddle.net/e8jn9pj5/3/

Or if you are populating it from button's value you may use .value as suggested by adeneo http://jsfiddle.net/t4c5yq24/

3 Comments

Nope, you don't need to do that at all, innerHTML works just fine. Also, innerText is IE specific, and not cross-browser, today using textContent is probably a better idea, but again, it's not needed here.
Also, I dont think innerText is a standard
I agree using textContent is better in case it is coming from content of another div. But yes most probably he is populating it from button's value so none of it is required.

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.