0

Basically I want to rephrase a <p> block but the element is null even though I gave it a value. Because of that I can't change the value of it. The weird thing about it, in some other code of mine the exact same thing worked out. Would be nice if someone could explain me my error.

For the understanding of the code. I wrote a quicksort and wanted to show the sorted array. I'm trying to grab my HTML box via the getElementById() Method.

The following code is necessary to know.

const textEl = document.getElementById("test");

function sort(array, low = 0, high = array.length - 1){
    let index;
    if (array.length > 1){
        index = partition(array ,low, high);
        if (low < index - 1){
            sort(array, low, high - 1);
        }
        if (index < high){
            sort(array, index, high);
        }
    }
    textEl.innerHTML = array;
    return array;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="quicksort.js"></script>
</head>
<body>
    <div class="div-1">
        <p class="array-el" id="test">Test</p>
    </div>
</body>
</html>
Heretic Monkey
  • 10,498
  • 6
  • 45
  • 102

1 Answers1

0

It is because you are running your javascript before the HTML loads. Put the script at the end of the body tag like so:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="div-1">
        <p class="array-el" id="test">Test</p>
    </div>
    <script src="quicksort.js"></script>
</body>
</html>
alec wilson
  • 158
  • 2
  • 11
  • 1
    While that is true, you don't necessarily need that as the solution. Since he is calling a function to update the text, he could simply move the `textEl` inside the function. – ShanerM13 Feb 08 '21 at 19:26
  • That is true, but it is in general still good practice to put scripts at the end of the body tag – alec wilson Feb 09 '21 at 04:18