JavaScript Needs to Send Esc Character \n or Text Return <p> to HTML/Browser
Asked Answered
S

1

0

1) When executing JavaScript in the interpreter - I can use an esc sequence to put some text on a second line NOTE: the value of myHeading.textContent was different in this screen shot than in the succeeding two

   > myHeading.textContent + " \n How are things?"
   < "Joshua Tree is swell, Laurel Ruth Shimer 
   How are things?" = $1

2) But when I use the same idea testing by calling html from a browser (Safari), the '\n' is, I would think, just seen as though I had done this within html - HTML doesn't do anything special when I put something on the next line. This makes sense, of course.

   var myHeading = document.querySelector('h1');
   myHeading.textContent = 'Good to see you again, ' + storedName +  ' \n    
  Write me again soon.' ;

enter image description here 3) If I attempt to add an html tag,

, that tag is just included as part of the text. It's not read by the html engine (I don't know what to call that) as actual characters

   var myHeading = document.querySelector('h1');
   myHeading.textContent = 'Good to see you again, ' + storedName +  ' <p>  
   Write me again soon.' ;

enter image description here ...

I a (maybe two?) Stackoverflow responses about putting html into an array, but I don't think that is the same thing.

Salaidh answered 13/5, 2016 at 15:28 Comment(0)
F
2

Whilst your shell does understand what \n represents, modern browsers do not. To represent a newline on a web page, you should use the <br> element instead.

Now, as you've already experienced, you cannot interpolate an HTML element using the textContent property. This is because the textContent property represents the text of an element, not the html -- any string you set will be treated as text.

To set the inner html of an element, use the innerHTML property.

Something like this should work for your needs:

myHeading.innerHTML = 
    'Good to see you again, ' + storedName +  ' <br>  Write me again soon.' ;
Foolish answered 13/5, 2016 at 15:31 Comment(1)
Alex's answer points out why it's really important that I'm working on reading the Flannigan O'Reilly JavaScript (Rhino) book straight through! I didn't yet know enough to look up 'innerHTML' in the index. However, it's also pretty useful to stop and make up examples like this, that put all the code snippets I try out together, and work with the 3 elements of the Client Side. I like studying JavaScript this way much better than using a tutorial based book, because my own interests keep me more motivated.Salaidh

© 2022 - 2024 — McMap. All rights reserved.