0

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

Community
  • 1
  • 1
abcf
  • 685
  • 2
  • 10
  • 25
  • Seems to work fine, both the LI and the image is there -> https://jsfiddle.net/adeneo/rxy7u4w2/ – adeneo Oct 22 '16 at 15:20
  • Oh hmm, I guess the attributes like src and href aren't appearing – abcf Oct 22 '16 at 15:37
  • 1
    Well, no, that's because you've created properties on the jQuery object. jQuery uses `img.attr('src','someimage.png')` to set attributes – adeneo Oct 22 '16 at 16:10

2 Answers2

1

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>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
0

You can try this way also

var li = '<ul id="list">'+
           '<li>'+
             '<a href="">'+
              '<img src="source_example" />'+
            '</a>'+
         '</li>'+
         '</ul>';
$("#list").append(li);
chhameed
  • 4,406
  • 4
  • 26
  • 44