0

I want to know how to add an HTML element with jQuery or Javascript after another element

for example, from this

<ul>
<li> .... </li>
<li> .... </li>
<li> .... </li>
</ul>

to this

<ul>
<li> .... </li>
<div>..</div>
<li> .... </li>
<div>..</div>
<li> .... </li>
<div>..</div>
</ul>
depperm
10.8k4 gold badges46 silver badges68 bronze badges
asked Jun 22, 2015 at 19:26
6
  • I would look at jquery after(), api.jquery.com/after Commented Jun 22, 2015 at 19:30
  • I tried the append() Method and after() Commented Jun 22, 2015 at 19:31
  • 3
    That is invalid HTML so the answer is NO Commented Jun 22, 2015 at 19:32
  • nothing work to me because when i used the element be After all the ul and i want it After every ul Commented Jun 22, 2015 at 19:36
  • Do you understand the issue after reading my answer below? A div can not be a child of a UL so you can not add the div after the li in the DOM tree. The ul expects to find li's as the children. When you try to add the div, it will try to figure out the best fit and it is probably adding the new div after the UL. Commented Jun 22, 2015 at 20:06

1 Answer 1

2

You can not append a divas a child of a UL so no you can not add the div element after the li. The browser will "fix" your bad HTML the best as it can and not every browser will do the same thing.

If you append and li that has a div as a child, it will work correctly.

$("li").after("<li><div>New</div></li>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
 <li> .... </li>
 <li> .... </li>
 <li> .... </li>
</ul>

answered Jun 22, 2015 at 19:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.