Learn to Code With JavaScript by Darren Jones

Learn to Code With JavaScript by Darren Jones

Author:Darren Jones [Nilson Jacques]
Language: eng
Format: epub
Publisher: SitePoint
Published: 2017-08-08T23:00:00+00:00


Updating the HTML

The easiest way to update the HTML on a page is to use the innerHTML property. This will return all the HTML that’s enclosed inside that element’s tags as a string. We can see this by entering the following code into the console:

hello.innerHTML; << "Hello, <em>World!</em>"

The great thing about the innerHTML property is that it’s also writable, so it gives us a convenient way to insert a chunk of HTML inside an element.

To demonstrate this, let’s add some JavaScript code into the JS section on CodePen to give a more personalized greeting. First of all, let’s make sure we have a reference to the heading:

const hello = document.getElementById('greeting');

Next, we’ll use a prompt box to ask the user for their name and store it in the variable name:

const name = prompt('What is your name?');

Last of all, we’ll replace the innerHTML property with our own personalized greeting, which uses the name variable that we’ve just collected from the user:

hello.innerHTML = `Hello, <em>${name}!</em>`;

Notice that we’ve used a template literal to produce the HTML. These are incredibly useful when creating chunks of HTML to dynamically insert into a web page, as they allow variables to be inserted directly into them.

If everything went to plan, you should see something like this (but hopefully with your name!):



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.