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
-
I would look at jquery after(), api.jquery.com/afterdepperm– depperm2015年06月22日 19:30:09 +00:00Commented Jun 22, 2015 at 19:30
-
I tried the append() Method and after()Soufiane Douimia– Soufiane Douimia2015年06月22日 19:31:05 +00:00Commented Jun 22, 2015 at 19:31
-
3That is invalid HTML so the answer is NOepascarello– epascarello2015年06月22日 19:32:31 +00:00Commented 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 ulSoufiane Douimia– Soufiane Douimia2015年06月22日 19:36:16 +00:00Commented 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.epascarello– epascarello2015年06月22日 20:06:56 +00:00Commented Jun 22, 2015 at 20:06
1 Answer 1
You can not append a div
as 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
default