Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create these nested dom elements with jquery?

Tags:

Given these javascript variables:

var div_id = "my_div"; var h1_class = "my_header"; var a_class = "my_a_class"; var a_string = "teststring"; 

and this page element:

<div id="container"></div> 

I want to build this html structure with jQuery:

<div id="container">     <div id="my_div">         <h1 class="my_header">             <a href="/test/" class="my_a_class">teststring</a>         </h1>     </div> </div> 

What is the best and most readable way to chain the commands here?

like image 624
Hobhouse Avatar asked Mar 15 '11 20:03

Hobhouse


People also ask

How can create DOM element in jQuery?

Answer: Use the jQuery append() or prepend() method You can add or insert elements to DOM using the jQuery append() or prepend() methods. The jQuery append() method insert content to end of matched elements, whereas the prepend() method insert content to the beginning of matched elements.

How do I add elements to my DOM?

To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.

What is DOM element in jQuery?

The Document Object Model (DOM) elements are something like a DIV, HTML, BODY element on the HTML page. A jQuery Selector is used to select one or more HTML elements using jQuery. Mostly we use Selectors for accessing the DOM elements.


1 Answers

UPDATED

  • DEMO: http://so.lucafilosofi.com/how-do-i-create-these-nested-dom-elements-with-jquery/

JSON

        var widgets = [{             "div" : {                 "id" : "my-div-1"             },             "h1" : {                 "class" : "my-header"             },             "a" : {                 "class" : "my-a-class",                 "text" : "google",                 "href" : "http://www.google.com"             }         }, {             "div" : {                 "id" : "my-div-2"             },             "h1" : {                 "class" : "my-header"             },             "a" : {                 "class" : "my-a-class",                 "text" : "yahoo",                 "href" : "http://www.yahoo.com"             }         }];          $(function() {             $.each(widgets, function(i, item) {                 $('<div>').attr('id', item.div.id).html(                 $('<h1>').attr('class', item.h1.class).html(                 $('<a>').attr({                     'href' : item.a.href,                     'class' : item.a.class                 }).text(item.a.text))).appendTo('#container');             });         }); 
like image 104
Luca Filosofi Avatar answered Oct 11 '22 07:10

Luca Filosofi