0

I use the following to create objects in JavaScript using jQuery:

var article_attrs = { 
        'class' : 'class-name',
        click : function_name,
        hover : function_name,
        html : $('<h2>', { html : "Heading" })
    },
    article = $('<article>', atricle_attrs);

This works great - by setting the html attribute I set the content of the article.

What I want to do at this point though, is add a <h2> tag, and a <div> tag including a <footer> tag. My outline for this element will look like:

  • article
    • h2
    • div
      • footer

What would be the best way of doing this? (Note this is an example only).

Update: The main question is, using the html attribute, how do I add multiple elements?

I have tried a method from a similar question, but it does not work in this case:

html : [ $('<h2>', { html : "Heading" }), $('<div>', { html : "Some content" }) ]

I have made this fiddle which works.. but my JS still doesn't. I'm definitely missing something.

Edit: Works with jQuery 1.8.* only

2
  • $("<element1>").add("<element2>") might do the trick. Commented Oct 2, 2012 at 10:43
  • @Shikyo: add() adds another element to the jQuery selection, I think the question is 'how do I append am element to a newly-created jQuery object?' Commented Oct 2, 2012 at 16:01

2 Answers 2

0

you could simply write like so

$('<h2></h2><div><footer></footer></div>').appendTo(article)
Sign up to request clarification or add additional context in comments.

1 Comment

I could, yes. However I like having control over all the attributes using object notation and would really like to find a method along the same lines.
0
var $myEle = $("<article />").append(
                 $("<h2 />").text("...")
             ).append(
                 $("<div />").append(
                     $("<footer />")
                 )
             );

You can nest jQuery .append() method calls like above to create the HTML structure you need. I like this method because it makes it easy to visualize what the HTMl structure will be when you read it.

The above code would render this HTML:

<article>
    <h2>...</h2>
    <div>
        <footer></footer>
    </div>
</article>

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.