简体   繁体   中英

h1 tag not working properly in javascript

I am a novice in JavaScript and need some help. I have to display name[i] in an h1 header, so say for instance I write in "John" it would be displayed as

nhoJ

but when I try to put the h1 header around name[i] as it is now, it is displayed like this:

n
h
o
J

Can anyone help me put an h1 header around name[i] and make it display properly?

<html>
<body>
    <script>
        var namIn = window.prompt("Enter Name, separated by space:" ); 
        var namAr = namIn.split("");
        var namArLen = namAr.length; 
        document.write(namAr + "<br /> Length: " + namArLen + "<br />"); 
        var name = namIn;
        for(var i = name.length - 1; i >= 0; i--) {
            document.write( "<h1>" + name[i] + "</h1>" );
        }
    </script> 
</body>
</html>

Open the <h1> tag before the loop and close it after the loop:

document.write("<h1>");
for(var i = name.length - 1; i >= 0; i--) {
   document.write(name[i]);
}
document.write("</h1>");
<html>
 <body>
    <script>
        var namIn = window.prompt("Enter Name, separated by space:" ); 
        var namAr = namIn.split("");
        var namArLen = namAr.length; 
        document.write(namAr + "<br /> Length: " + namArLen + "<br />"); 
        var name = namIn;
        document.write("<h1>");
        for(var i = name.length - 1; i >= 0; i--) {
            document.write(name[i]);
        }
        document.write("</h1>");
    </script> 
  </body>
</html>

alternative instead of the loop:

document.write("<h1>" + name.reverse() + "</h1>");

you are giving h1 in every loop, to solve your problem, do this step

pseudo code:

open h1
loop 
  name[i]
close h1

thats it

You are creating a new node for each letter, you need to concatenate the characters then write the html node, try something like this:

var newName = "";
for(var i = name.length - 1; i >= 0; i--) {
    //reverse.push(name[i]);
    newName += name[i];
}
document.write( "<h1>" + newName + "</h1>" );

You are writing too many <h1> tags. Each of these tags write one line in the document.

Hence each character appears on a seperate line.

You should enclose the whole name in a single <h1> tag.

You can do this by:

document.write("<h1>");
for(var i = name.length - 1; i >= 0; i--) {
    document.write(name[i]);
}
document.write("</h1>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM