abcf abcf - 1 month ago 6
jQuery Question

Appending multiple elements to html

I've seen on SO this example to append an element

jQuery('<div/>', {
id: 'foo',
href: 'http://google.com',
title: 'Become a Googler',
rel: 'external',
text: 'Go to Google!'
}).appendTo('#mySelector');


but I'm trying to create this structure

<ul id="list">
<li>
<a>
<img src="source_example" />
</a>
</li>
</ul>


The UL element will already exist, so I'm just going to create new LI, A, and IMG elements.

right now I'm doing this

li = $("<li />");

a = $("<a />");
a.href = "href";
a.id = "pic";

img = $("<img />");
img.id = "id";
img.src = "src";
img.width = "100";
img.height = "100";

a.append(img);
li.append(a);
$("#list").append(li);


But it's only appending an empty li to the #list ul. It's not showing the img or anchor tags. I would use the SO method above, it is also cleaner, but I don't have id attributes for each li nor do I really want to add ids to each li

Answer

Before you need to create your new element and after you can append it to your dom element.

In order to create your structure you need:

  1. create the ul node
  2. append to this node the li node
  3. append to the li node the anchor node
  4. ...and finally the image

This new element can be now appended to your element:

$('<ul/>', {id: 'list'})
    .append($('<li/>')
        .append($('<a/>')
            .append($('<img/>', {src: 'source_example'}))
)).appendTo('#mySelector');


//
// debug print
//
var tabs = 0;
console.log(document.querySelectorAll('#mySelector ul')[0].outerHTML.replace(/><./g, function(match) {
  if (match[2] == '/') {
    tabs -= 3
  } else {
    tabs += 3
  }
  return '>\n' + ' '.repeat(tabs) + match.substr(1);
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="mySelector">
    <p>This is my element</p>

</div>