abcf abcf - 3 years ago 134
jQuery Question

Appending multiple elements to html

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

jQuery('<div/>', {
id: 'foo',
href: '',
title: 'Become a Googler',
rel: 'external',
text: 'Go to Google!'

but I'm trying to create this structure

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

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"; = "pic";

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


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 Source

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($('<img/>', {src: 'source_example'}))

// 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=""></script>

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download