Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

When using the createElement function, where does the "." and the element create name comes from in the function?

const createElement = (elementName, property, value)=>{
          const element = document.createElement(elementName);
                element[property] = value;
                return element;
    }

Maybe I am over thinking, I am just trying to make sense of it. But, in the video when we call the function createElement, to create a span.

How does the variable name "element" change to "span". When we name it as "element" in the createElement function

const "element" = document.createElement(elementName);

And how does "[property]" add the "." , when in the parameter we never add a "."

const span = createElement("span", "textContent", text);                                            

why wasn't the span element it created like this? With a "." in the parameter?

const span = createElement("span", ".textContent", text);

1 Answer

Steven Parker
Steven Parker
231,269 Points

There are two different ways to access a property in an object. One way is with the dot notation (example: element.textContent), and the other is with bracket notation (example: element["textContent"]),. The membership operator (the dot) is not used in bracket notation.

Dot notation can only be used when the property name is known in advance. But in this function, the property name is being passed as an argument, so bracket notation is needed.

Also note that there is an error in your 2nd example, since variable names (like element) can not have quotes around them. Quotes create a string literal, and those cannot be assigned to.