0
var div =  {
  element:'div',
  parent:'body',  
  style: {
    width:'100px',
    height:'100px',  
    border:'1px solid black'
  }

  child: {
    element:'input',
    type:'text',
    name:'age',
    value:'22'
  }
}

I want to pass this object to a function and the function will recursively create the dom elements

There is a main div and there is a child element input associated with it. The main div has some style which is also applied dynamically.

How can i do this?

5
  • Let's start with this: There is a comma missing after the style property. Is that just a typo? And where is the recursion? Can there be multiple children? Can a child have a child? Commented Jul 25, 2015 at 8:50
  • github.com/shreeramneupane/doc/blob/master/js/file.js might help you to get answer. Commented Jul 25, 2015 at 8:53
  • Yes there can be multiple child and chld can have child and sorry that was a typo Commented Jul 25, 2015 at 9:03
  • I don't understand what the problem is. Just write a function which does what you want. Commented Jul 25, 2015 at 9:05
  • @RanojitBanerjee How are multiple children structured? Are they named child, child2, child3 or can the child property either be an object for 1 single child or an array for multiple children? You need to give us some more information. Commented Jul 25, 2015 at 9:08

1 Answer 1

1

I wrote a library called art.js for a similar purpose.

With art.js you can define DOM elements in a tree-like fashion using nested function calls. Objects literals can be used to apply properties to elements.

Then, to get what you want, you could use this code:

var div = art(
    'div', 
    {
        style:
        {
            width: '100px',
            height: '100px',  
            border: '1px solid black'
        }
    },
    art(
        'input',
        { type: 'text', name: 'age', value:'22' }
    )
);
art(document.body, div);

The documentation also shows examples on how to add event listeners.

Sign up to request clarification or add additional context in comments.

Comments

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.