tags:

views:

54

answers:

2

I'm trying to replace a div with created elements, going from:

<div id='links'></div>

to

<div id='links'>
<ul>
<li><a href='#'>No</a></li>
</li>
</div>

I want to attach a function to the link in the <a> element that I create. Creating the desired link is working, but wrapping the link in an <li> element and a <ul> element using the wrap function isn't working:

var no = $('<a>').attr({
    href: '#'
  }).click(function () {
    alert('clicked no');
    return false;
  }).text('no');

Works, but no.wrap('<li></li>'); still just gives me an unwrapped <a> element. I've also tried $('#links').append('<ul>').append('<li>').append(no) but that doesn't work either.

Is there a better way to do this?

A: 

no.wrap('<li></li>') will still return the <a> element, but it adds a <li> element around it. So you can do no.wrap('<li></li>').parent() to wrap it and return the <li> element.

Lukáš Lalinský
A: 
<script type="text/javascript">
$(function(){

    var list = $("<ul />");

    var no = $('<a />')
     .attr({ href: '#' })
     .click(function () {
      alert('clicked no');
      return false;
     })
     .text('no')
     .wrap("<li />")
      .parent()
      .appendTo(list);

    list.appendTo("#links");
});    
</script>
Juraj Blahunka