I'm confuse
I'm confuse

Reputation: 13

Uncaught TypeError: Cannot read property 'innerHTML' of null at text inside this blog website I'm trying to write

var x = 0;

function text() {
  var blogtext = document.getElementById("Textarea").value;
  var y = "p" + String(x);
  console.log(typeof y);
  //problem
  document.createElement("p").id = y;
  //
  document.getElementById(y).innerHTML = blogtext;
  //document.write("<p>"+blogtext+"<p>");
  x = x + 1;
}       

When I run this code inside an HTML file the error: Uncaught TypeError occurs, the code is supposed to create a new paragraph tag whose content is the text inputted by the user inside the text area and each paragraph would have a different id as x increases. Sorry, I'm new to coding this is one of my school's projects.

Upvotes: 0

Views: 531

Answers (4)

user13604617
user13604617

Reputation:

You are not creating and appending the element coreectly

    var x = 0;

    function text() {
      var blogtext = document.getElementById("Textarea").value;
      var y = "p" + String(x);
      console.log(typeof y);

     var elem = document.createElement("p")
     document.body.append(elem)
     elem.id = y

     elem.innerHTML = blogtext;

      x = x + 1;
      console.log()
    } 

Upvotes: 1

dqve
dqve

Reputation: 609

You made a few omissions in your code and just a bit of cleanup solves your problem

var x = 0;

function text() {
  var blogtext = document.getElementById("Textarea").value;
  var y = "p" + String(x);
  console.log(typeof y);
  //solution
 var p = document.createElement("p")
 document.body.append(p)
 p.setAttribute("id",y)
  //
 p.innerHTML = blogtext;
  //document.write("<p>"+blogtext+"<p>");
  x = x + 1;
  console.log()
} 

//text()
<textarea id="Textarea" onChange=text()></textarea> <br>

Upvotes: 1

Umutambyi Gad
Umutambyi Gad

Reputation: 4101

append your paragraph to the DOM, check out for this one i made

 var x = 0;
function text() {
    var blogtext = document.getElementById("Textarea").value;
    var y = "p" + String(x);
    console.log(typeof y);
    var x =document.createElement("p").id = y;
    document.body.appendChild(x);
    document.getElementById(y).innerHTML = blogtext;
    x = x + 1;
}

Upvotes: 1

epascarello
epascarello

Reputation: 207537

You are not creating the element right and you are looking for the element before it is added to the page.

var x = 0;
function text() {
    var blogtext = document.getElementById("Textarea").value;
    var y = "p" + String(x);
    // create the element
    var p = document.createElement("p")
    //set the id
    p.id = y;
    //set the html
    p.innerHTML = blogtext;
    // add it to the page
    // document.getElementById("outputId").appendChild(p)
    document.body.appendChild(p)
    x = x + 1;
}

Upvotes: 3

Related Questions