I am writing a code to encode a string and it hopes to display the encoded string in a div. However, it shows nothing. May I know what's wrong with my code? Thank you.
HTML:
<div id="c"></div>
Javascript:
function encode() {
var a = "abcde";
a = unescape(a);
var c = String.fromCharCode(a.charCodeAt(0) - a.length);
for(var i = 1; i < a.length; i++){
c += String.fromCharCode(a.charCodeAt(i) - c.charCodeAt(i - 1));
}
return c;
document.write(c)
}
You're writing the output to the document after returning from the function. Try something like this:
function encode (){
var a = "abcde";
a = unescape(a);
var c = String.fromCharCode(a.charCodeAt(0) - a.length);
for(var i=1; i<a.length; i++){
c+=String.fromCharCode(a.charCodeAt(i) - c.charCodeAt(i-1));
}
return c;
}
document.getElementById("c").innerText = encode();
<div id="c"></div>