1

I'm trying to copy the contents of a DIV and insert a heading before the copy. However, the heading gets inserted at the wrong point.

var reference = $('#reference').clone().contents();
reference.prepend('<h1>Heading</h1>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="reference">
  <ul>
    <li></li>
  </ul>
</div>

I want the heading to go before the <ul> but instead it gets inserted after before the first li.

So it looks like this:

<div id="copy">
  <ul>
    <h1>Heading</h1>
    <li></li>
  </ul>
</div>

Instead of this (what I want):

<div id="copy">
  <h1>Heading</h1>
  <ul>
    <li></li>
  </ul>
</div>

This is probably a really basic question but a few hours of trying prependTo(), before(), insertBefore() and searching online have not gotten me any closer. Thanks :)

3
  • 2
    Possible duplicate of add element before some element Commented Feb 23, 2017 at 7:50
  • maybe something like this? var reference = $('#reference > ul').clone().contents(); Commented Feb 23, 2017 at 8:02
  • try using- $('#reference').clone().contents().parent().prepend('<h1>Heading</h1>') Commented Feb 23, 2017 at 8:31

2 Answers 2

2

Firstly remove contents() as you want to clone the whole element, not its children. Secondly, create the h1 tag, then use prependTo() to place it at the desired location in the cloned element.

Also note that your current code results in duplicate id attributes in the DOM, which is invalid. I'd suggest making the #reference id in to a class instead. Try this:

var reference = $('.reference:first').clone();
$('<h1>Heading</h1>').prependTo(reference);

$('body').append(reference);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="reference">
  <ul>
    <li>Foo</li>
  </ul>
</div>

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

2 Comments

Thanks for your speedy response! I made a few mistakes in my original question - I did actually only want the contents of #reference and using prependTo() still results in the heading being inserted after the <ul>. I've edited and corrected my original question
I'm still not clear on exactly what you want. Can you edit the question to show the HTML you expect to have after the jQuery has run including the cloned content
0

Use it like this I have tried and It is working fine.

$('#reference').clone().contents().parent().prepend('<h1>Hea‌​ding</h1>')

1 Comment

This actually does exactly what I needed to do. Thanks! :o)

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.