0

I created an id for the variable I wanted to use but can't find how to insert it in the p element. When I try this I get "Uncaught type error: cannot set property of 'innerHTML' of null(...).

var str = array.toString();
       document.getElementById('variable').innerHTML = str;
<p> Start of sentence  <id = "variable" />,  end of sentence</p>

answer to this question is to use span tag.

Saurav
  • 15
  • 5

2 Answers2

3

If the code is exactly as in your snippet, then it's not working for 2 reasons;

  1. You're trying to getElementById before the DOM contains the element with id 'variable' - to solve that run the script on page load or at least after the element is declared.

  2. I've never seen anyone do

     <id="variable"/> 
    

and try to reference it, I would do

    <span id="variable"></span>

and reference that with getElementById.

Aᴍɪʀ
  • 6,664
  • 3
  • 36
  • 48
1

Your HTML syntax is wrong.

Instead of

<p> Start of sentence  <id = "variable" />,  end of sentence</p>

You should have:

<p id="variable"> Start of sentence  ,  end of sentence</p>

Id is an attribute, not a tag. Therefore, it must be nested within a tag, in this case the <p> tag.

nmg49
  • 1,266
  • 1
  • 10
  • 26
  • Sorry we only briefly went over html but i'm trying to get the variable inside the middle of my sentence without creating a new paragraph. – cameron schuster Nov 03 '16 at 03:18
  • You can't do this with plain HTML/Javascript, you need some kind of templating framework (by this I mean your id syntax). I've never seen this kind of syntax before. What templating library are you using? – nmg49 Nov 03 '16 at 03:20