0

So I have this code here that I want to use to dynamically make elements, but it does not work:

make = {};
elements = ['a', 'div', 'span', 'form', 'h1', 'h2', 'h3', 'h4'];
elements.forEach(function(element){
    make[element] = function() {
        document.createElement(element);
    }
})

However, when I do:

var h1 = make.h1();

I get undefined... Can anyone explain why the element param I am passing to the createElement function doesn't work? I inspected this to dry and debug and I noticed that the make object has all the correct properties and corresponding functions, however the createElement function doesn't seem to retain the correct value of the element I am tying to pass.

DISCLAIMER: I know there are tons of libraries that I can use but I am doing this for learning and understanding purposes. Thank you to anyone who takes some time to explain this to me. :]

3 Answers 3

4

You're just missing a return statement:

return document.createElement(element);
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, thank you. The reason I didn't think of this is because the instructions I'm following states that the createElement function creates and returns an element. I didn't realize that I also had to return that element. Now I feel silly, but thank you so much!
@dreamcod3r You're welcome. It does return the element, but only to the function you call it from, not to the function that originally called that. There are no functions in JavaScript that return from where they are called (they return to where they are called, but not fro there).
2

This is a more functional approach

let elements = ['a', 'div', 'span', 'form', 'h1', 'h2', 'h3', 'h4']
let make = elements.reduce((acc, elem) =>
  Object.assign(acc, { [elem]: document.createElement(elem) }), {})

console.log(make)

Output

{
  "a": <a></a>,
  "div": <div></div>,
  "span": <span></span>,
  "form": <form></form>,
  "h1": <h1></h1>,
  "h2": <h2></h2>,
  "h3": <h3></h3>,
  "h4": <h4></h4>
}

Comments

-1

since it is a function passing a array and return a array, I think Array.map is the best fit. see the code below:

elements = ['a', 'div', 'span', 'form', 'h1', 'h2', 'h3', 'h4'];
const make = elements.map(function(element){
    return document.createElement(element);
})

2 Comments

it's not supposed to return an array
Sorry, made a mistake. In this case, have to use reduce instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.