开发者

How do I wrap individual elements with the same tag?

开发者 https://www.devze.com 2023-01-22 10:32 出处:网络
I am trying to wrap individual li tags with a nested ul. For example I want the first HTML snippet, to be the second:

I am trying to wrap individual li tags with a nested ul. For example I want the first HTML snippet, to be the second:

Snippet #1

          <ul class="lof-main-wrapper">
            <li class="featured">
              <h3><a href="#">Title</a></h3>
              <a href><img src="" /></a>
              <p class="kicker"></p>
              <p class="summary"></p>
            </li>

            <li class="featured">
              <h3><a href="#">Title</a></h3>
              <a href><img src="" /&g开发者_运维知识库t;</a>
              <p class="kicker"></p>
              <p class="summary"></p>
            </li>
           </ul>

Snippet #2

          <ul class="lof-main-wrapper">
            <ul>
             <li class="featured">
               <h3><a href="#">Title</a></h3>
               <a href><img src="" /></a>
               <p class="kicker"></p>
               <p class="summary"></p>
             </li>
            </ul>

            <ul>
             <li class="featured">
               <h3><a href="#">Title</a></h3>
               <a href><img src="" /></a>
               <p class="kicker"></p>
               <p class="summary"></p>
             </li>
            </ul>
           </ul>

I am currently using the .wrap() function, which does what I want, but it duplicates the child elements into each nested ul, adding me more content to the DOM than what should be.

How do I prevent the duplication from occurring without painstakingly using the .remove() method to get rid of the duplicates?

FYI - I'm new to jQuery and JS in general, so any direction you can provide is appreciated.

Thanks,

Brion


You shouldn't wrap it to where a <ul> is directly inside a <ul> since that's invalid markup.

However, you can wrap them validly in a <li> with a <ul> inside using .wrap() to wrap each element the selector finds, like this:

$("#lof-main-wrapper li").wrap("<li><ul></ul></li>");


Use the wrap method

$('.lof-main-wrapper li').wrap('ul');

but as @Nick mentions in his answer, what you are trying to do is invalid, in HTML terms..

About the duplication you mention, you would have to show us the jQuery code you use..

0

精彩评论

暂无评论...
验证码 换一张
取 消