How to use jquery selector to add open div tag?

Possible duplicate:
Using .after () to add html closing and opening tags

I need to add HTML before <li> and after the same <li> .

The selector works, but when it adds HTML, it also closes the <div> with the addition </div> . I need it to be open.

my code is:

 $('#ja-megamenu .level1').before('<div class="childcontent cols1 ">'); 

Note: I need to add ONLY <div class="childcontent cols1 "> to li (with class = "level1")

then later I will use:

  $('#ja-megamenu .level1').after('</div>'); 

to add closure </div>

This code does not work. How can I make this work?

I read the documentation all day, but have not yet found the answer ...

Thanks: -)

+4
source share
5 answers

Although this HTML is not valid ( <li> parent cannot be <div> ), you can use wrap() :

 $("#ja-megamenu .level1").wrap("<div class='childcontent cols1' />"); 
+3
source

You cannot do this if you want to add a div around an element, use jQuery wrap () .

 $('#ja-megamenu .level1').wrap('<div class="childcontent cols1 "></div>'); 

BUT the problem you have is a div can't wrap li! You need to do something else.

+4
source

Try using wrap if you want your html to be tried before and after.

 $('#ja-megamenu .level1').wrap('<div class="childcontent cols1 ">'); 
+1
source

use wrap ...

 $('#ja-megamenu .level1').wrap('<div class="childcontent cols1">'); 
+1
source

First of all, this is an invalid operation because you cannot add a div before or after li ,

the li element must be in the ul or ol container, and its siblings must be li .

try changing the structure: maybe put a div inside li

 <ul> <li class="level1"><div></div></li> <li></li> <li></li> </ul> $('.level1').prepend('<div> Your content here</div>'); 
+1
source

Source: https://habr.com/ru/post/1440533/


All Articles