skip to Main Content

In this website, if the letter entered is a new line, a new line would be returned, I have this like as follows

if (character === 'n'){
   element = document.createElement('br');

I tried adding var before, or even changing the single quotations to double, what is wrong with it?

Thank you in advance

2

Answers


  1. Please add further information on what you are trying to do and provide a minimal reproducable example.

    It looks like you don’t add the element to the body, so maybe try this:

    if (character === 'n')
    {
       var element = document.createElement('br');
    }
    
    document.body.appendChild(element);
    

    This won’t add the element automatically on any keystroke. For that, you need to listen to the keydown event.

    Login or Signup to reply.
  2. You need to then append that element with document.appendChild(element)
    https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild

    It looks like you’re doing this inside a loop, so either create the HTML string all as one (as in the below snippet) or add the element like so:

       if (character === 'n'){
           element = document.createElement('br');
           document.appendChild(element)
    
    // string to show on page
    const stringToShow = `something
    on a new
    line`;
    
    
    // create element and content
    const divElement = document.createElement("div")
    const content = stringToShow.split("n").join("<br />")
    
    // add content as HTML
    divElement.innerHTML = content;
    // append child to body, or any element for that matter
    const elementToAppendTo = document.body
    elementToAppendTo.appendChild(divElement)
    
    
    // if (character === 'n'){
    //    element = document.createElement('br');
    //    document.appendChild(element)
    <body></body>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search