skip to Main Content

I am learning JavaScript, and I am working on this code, but part of it requires me to continuously send new alerts to the screen. I found a way to print the messages straight on the screen, and it works perfectly.

I’m just wondering if there is a way to shorten it further. It’s not a super big issue, other than it looks cleaner to me, but mostly its just once i get an idea in my head i want to figure how to do it. For example, as you can see in the code below, right now I use:

const show = document.getElementById('htReadOut');

show.innerHTML = `some text`;

BUT I’d like to reduce the second line further to just be

print = `some text`;

I tried making a function and an object type, but get an error that the the id’s in the new html aren’t defined.

I tried making a constant variable so that print would be short for show.innerHTML, but I get an error when I try to use "print = someText" since it thinks I’m trying to redefine print.

2

Answers


  1. Set your code like this. Then, you can use the print function as much as you want to print the message to the screen. If you are only using show with text, you don’t need to use innerHTML, it is enough to just use innerText like in the example below.

    const show = document.getElementById('htReadOut');
    
    function print(message) {
        show.innerText = message;
    }
    
    print("Hello"); 
    
    Login or Signup to reply.
  2. hello you can try this…

    const show = document.getElementById('htReadOut');
    
    function print(element, sometext) {
        element.innerHTML = sometext;
    }
    
    print(show, 'Hello, world!');
    

    every time when you have an element you want to write text in it, just pass that element and the text into the print function

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search