0

I'm using bootstrap 3.0 to make a nifty looking sidebar. I'm looking to clone the current little bit of HTML with jQuery and append it to the page:

<a class="list-group-item" href="#">
                <div class="list-group">
                <h4 class="list-group-item-heading">Upcoming awesome</h4>
                <p class="list-group-item-text">Awesome stuff is here</p>                
                </div>
            </a>

and JS

 $(document).ready(function () {
            $appts = $('a.list-group-item > div').contents().andSelf().clone()
            $appts.appendTo('body');

        });

Currently, I'm not getting the behavior I hoped, and you can see that here

I know that HTML4 doesn't allow divs inside of anchor tags, but I'm using Chrome and I still can't get the styling right (notice that bootstrap CSS and bootstrap.js are included in the fiddle). I've got a couple questions:

  1. Why isn't the newly appended jQuery object being styled the same way as the one that's included in the source?
  2. Why is jQuery appending the an extra copy of the initial jQuery object?
4
  • 1
    Is this what you want? jsfiddle.net/QqMD9
    – Jason P
    Oct 10, 2013 at 20:23
  • Not sure what version of jQuery your using but here is something to be mindful of: "Note: This function has been deprecated and is now an alias for .addBack(), which should be used with jQuery 1.8 and later." per the API docs for .andSelf().
    – War10ck
    Oct 10, 2013 at 20:25
  • 1
    @JasonP Yeah, that's it. I had that initially, but for some reason it wasn't being styled after I appended it. I'll have to figure out why that's happening in my actual project. Oct 10, 2013 at 20:26
  • 1
    beacause you are targeting the first div under the anchor element. Try 'a.list-group-item' as your selector
    – elmasse
    Oct 10, 2013 at 20:27

1 Answer 1

2

I'll answer your questions in order.

  1. The reason the styling is different is because the styling is applied to the <a> tag and you are cloning the content within the <a> tag, not the tag itself.
  2. Jquery is appending both the contents of the selector and the selector, which means you are seeing double.

If you would like to append the styled a tag, the following snippet should work:

$(document).ready(function () {
    // store a copy of the container 'list-group-item'
    $appts = $('a.list-group-item').clone()
    // append that copy
    $appts.appendTo('body');
});

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.