-2

My Code:

var cat, inputdat;
var KeyUrl = "someurl";
cat = ["abc", "def", "ghi"];
var fLen = cat.length;

for (i = 0; i < fLen; i++) {

  inputdat += "<label for=\"" + cat[i] + "\">" + cat[i] + "</label><br><input type=\"text\" id=\"" + cat[i] + "\" name=\"" + cat[i] + "\" value=\"\"" + cat[i] + "\"><br><a href=\"" + KeyUrl + document.getElementById(cat[i]).value + "\" rel=\"nofollow\">Here</a><br>";

}
inputdat += "<br/>";
document.getElementById("res").innerHTML = inputdat;
<h2 id="res">hello</h2>

The error:

{
 "message": "TypeError: document.getElementById(...) is null",
 "filename": "https://stacksnippets.net/js",
 "lineno": 19,
 "colno": 202
}```

Part of the code causing the error:

href=\""+KeyUrl+document.getElementById(cat[i]).value+"

I am trying to append the value of the input to my keyurl but I am getting null.

ZF007
  • 3,708
  • 8
  • 29
  • 48

1 Answers1

1

Looks like there isn't an element with id abc, or the rest of the array cat.

You should run a loop that iterates through cat and checks if there is an element with ID cat[i]. Here is how that looks:

for (var i = 0; i < cat.length; i++) {
    if(!document.getElementById(cat[i])) {
        var div = document.createElement("div");
        div.id = cat[i];
        div.setAttribute("value", `alert('this is a test: ${i+1}')`);
        document.body.appendChild(div);

    }
}

The line document.getElementById(cat[i]) returns null because there is no element with such an ID, but the above code should fix that. Here is how I tested the code, if that will help:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

<h2 id="res">hello</h2>


<script type="text/javascript" defer>
var cat, inputdat;
inputdat = "";
var KeyUrl = "javascript:"; // CHANGE THIS URL, IT IS JUST AN EXAMPLE
cat = ["abc","def","ghi"];
var fLen = cat.length;


for (var i = 0; i < cat.length; i++) {
    if(!document.getElementById(cat[i])) {
        var div = document.createElement("div");
        div.id = cat[i];
        div.setAttribute("value", `alert('this is a test: ${i+1}')`);
        document.body.appendChild(div);

    }
}




for (i = 0; i < fLen; i++) {

    console.log(cat[i]);
    
    inputdat += `<label for="${cat[i]}">${cat[i]}</label><br><input type="text" id="${cat[i]}" name="${cat[i]}" value="${cat[i]}"><br><a href="${KeyUrl+document.getElementById(cat[i]).getAttribute("value")}" rel="nofollow">Here</a><br>`;


    inputdat += "<hr/>";
    
}

document.getElementById("res").innerHTML = inputdat;
</script>


</body>
</html>
Krokodil
  • 1,165
  • 5
  • 19
  • 1
    yes - there isn't an element with the `ID`s in the array. That is why when the script tries to find `#abc`, `#def`, or `#ghi` it returns `null`, which obviously does not hold the property "`value`" – Krokodil Nov 24 '20 at 18:10