Web primitives

Some things we can do

  • Get an element that already exists in the HTML.

  • Create a new element and add it to the page

  • Set the text of an element.

  • Add a function to be called when an element is clicked. (Called a “click handler”.)

  • Get the clicked element from the event object passed to a click handler.

Getting existing elements

Assume our HTML contains this markup.

<div id="thing"></div>

How can we get ahold of the element representing that div in our Javascript?

document.querySelector('#thing');

The string '#thing' is a selector that says, “get the element whose id attribute is "thing".”

Holding onto an element

We can use document.querySelector whenever we want to get ahold of an element but sometimes it’s convenient to store a reference to the element in a variable so we can refer to it more easily:

const thing = document.querySelector('#thing');

// now we can use thing to refer to the element

Creating new elements

How can we create an element that is not already part of the HTML?

const element = document.createElement('p');

And how do we add it to the page?

document.body.append(element);

Or to another element?

anotherElement.append(element);

Setting the text of an element

Whether an element was in the HTML originally or we added it from Javascript, we can set the text of the element in the same way.

Assume element is a variable holding a reference to an element. How do we set its text?

element.innerText = 'hello, world!'

Adding a click handler

Assume, again, that element is a variable referencing an element. What property do we need to set to install a click handler on that element?

element.onclick = handler;

What kind of value does handler have to be?

A function, e.g.

const handler = (e) => {
  console.log('The element was clicked.');
};

Getting the clicked element

In a click handler, the clicked element the handler is attached to is available from the event argument that is passed to the handler. What is the name of the property?

e.currentTarget

For instance, to set the text of a clicked element we can write a function like:

const setOwnText = (e) => {
  e.currentTarget.innerText = 'I was clicked!';
};