0

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?

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1
<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>

Comments

0

With jQuery can actually just nest everything into a wrapper, especially if you don't need to address the individual items themselves.

You can also create new elements to be nested on the fly. No need to create a bunch of temporary variables to hold them all.

Multiple items can be appended at the same time by simply passing them all as separate parameters to append().

var wrapper = $('<div/>', {
  id: 'links'
});

$(wrapper).append(

  $('<ul/>').append(

    $('<li/>').append(
      $('<a/>', {
        href: '#',
        text: 'Yes'
      })
    ),

    $('<li/>').append(
      //you can even keep going! 
      $('<a/>', {
        href: '#',
        text: 'No'
      })
    ),

    $('<li/>').append(
      $('<a/>', {
        href: '#',
        text: 'Maybe'
      })
    )
  )

);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.