- Create HTML Elements
- Add attributes to the element
- Add event listeners to the element
- Add children elements to the element
I think that is a good start and hopefully simple enough we don’t feel overwhelmed. Below is a function that will do most of what we want. I’ll explain it in greater detail below.
Line three, we check to see if the attribute parameter is an object. If it is, we’ll need to iterate through the key/values and set those on our element. The easiest way to do this is by getting an array of keys from the object. Luckily, we can do this with the Object.keys() method. Now we can get the number of attributes by using the length() method on the array. Iterating over the keys gives us an index, which helps us access data in the attributes. In the keys array, we have each key stored, and can access it by the index location in the array. Getting the value of the attribute is also fairly easy using the current key of the iteration. We use the current key to access the value of the attributes passed to the function. In each iteration, we use that information to set the attributes on the element we created.
Next, on line number twelve, we check if any child elements are passed to the function. If they are, then we append them to our element.
Lines sixteen through twenty-three are very similar to three through ten. The only different is that we are adding event listeners to our element instead of setting attributes on our element. We could probably extract this to a function so we don’t have duplicate code, but I think it’s fine for this example.
If you want to ask questions, feel free to comment below, or even better use my new online community. Check out an article I wrote on Contributing to Open Source Projects on the Bulldog Creative Services Blog. The Bulldog Blog is using AMP HTML, so it should be fast!