Creating HTML Using JavaScript

What is JavaScript?

The code we use to make websites interactive and dynamic

 

 JavaScript has lots of possible uses, but we'll be talking about using it in conjunction with HTML

JavaScript in the DOM

DOM stands for Document Object Model. The DOM is a representation of HTML as objects that browsers create for us.

 

Objects are just a way to store data in JavaScript.

 

We'll be using the document object (that the browser creates for us) to access HTML, change its content and styling, and even add in new elements to our webpages.  

JavaScript in the DOM

Variables

Variables are what we use to store values in JavaScript.

 

We'll be using the "var" keyword to declare our variables. 

JavaScript variables are similar to variables in math

Data Types

number

string

var myNum = 4;
var price = 19.99;
var myStr = "Devmountain";
var numStr = "3901";

Data types are used in JavaScript to let our code know what kind of data it's working with -- we can store these in variables to use and manipulate

Selecting HTML Elements

We can also store HTML in variables.

 

We'll use the querySelector method to access the HTML and we'll store it in a variable. 

var myBtn = document.querySelector('#fav-btn')
var mainHeader = document.querySelector('header')
var firstBox = document.querySelector('.box')

Manipulating HTML

Now that we know how to select and store elements, let's talk about changing them and adding more.

textContent

createElement

appendChild

var btn = document.querySelector('#submit')
console.log(btn.textContent) // 'submit'
var myList = document.createElement('ul');
var mainNav = document.querySelector('nav');
var homeBtn = document.createElement('button');
homeBtn.textContent = 'Home';
mainNav.appendChild(homeBtn);
<button id='submit'>submit</button>

HTML:

JavaScript:

console.log

console.log is built in to JavaScript and ready for you to use

 

it allows us to print values into the console which is super useful, especially in learning and debugging

// here's what it looks like to use console.log
console.log('Hello World') 
   // Hello World

// next, let's say we have a variable, myVar, whose value we're unsure of
var myVar = "Devmountain rocks!"
console.log(myVar) 
   // "Devmountain rocks!"

// we can log multiple things too, just separate with commas
var pOneScore = 3
var pTwoScore = 5
console.log("player one:", pOneScore, "player two:", pTwoScore) 
   // player one: 3 player two: 5

Creating HTML Using JavaScript

By Devmountain

Creating HTML Using JavaScript

  • 1,144