Trouble outputting


#1


It doesn't output the sorted array and the length


<!DOCTYPE html>
<html>
<body>

<script>
var fruits = ["Apple", "Banana", "Orange", "Pear", "Fruit"]

console.log(fruits.sort())

console.log(fruits.length)
</script>

<body>

<html>


#2

did you open the console?

it will not display on the webpage, but that is not the purpose of console.log


#3

No, I want to display it on a webpage but I don't know how so I used console.log instead


#4

but console.log will log to the console?

well, the easiest is document.write():

document.write(fruits.sort())

this has one massive problem: it will overwrite everything on the webpage.

so something better to do would be:

<!DOCTYPE html>
<html>
<head>
<script>
var fruits = ["Apple", "Banana", "Orange", "Pear", "Fruit"]
document.getElementById("sort").innerHTML = fruits.sort();
document.getElementById("length").innerHTML = fruits.length;
</script>
</head>
<body>
<p id="sort"></p>
<p id="length"></p>
</body>
<html>

#5

Thanks, I was planning on using document.write but it didn't look right.


#6

okay, it seems this poses a security risk, use textContent instead:

document.getElementById("sort").textContent = fruits.sort();
document.getElementById("length").textContent = fruits.length;

#7

It still doesn't display anything??


#8

ah yes, i ran the code on jsbin, there you can trigger to get the js code to run.

nothing is executing the js code, you could make a button:

<!DOCTYPE html>
<html>
<head>
<script>
var myFunction = function(){
    var fruits = ["Apple", "Banana", "Orange", "Pear", "Fruit"]
    document.getElementById("sort").innerHTML = fruits.sort();
    document.getElementById("length").innerHTML = fruits.length;
}
</script>
</head>
<body>
<input type="button" value="click me" onclick='myFunction()'>
<p id="sort"></p>
<p id="length"></p>
</body>
<html>

#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.