简体   繁体   中英

How to add html element around another html element using jquery

Another day, another problem. I have something like that:

<p class="checkbox">
   <input name="cgv" id="cgv" value="1" type="checkbox">
   <label for="cgv">Some text.</label>
</p>

Using jquery I want to change this code to:

<p class="checkbox">
   <div class="checker" id="uniform-cgv">
      <span>
         <input name="cgv" id="cgv" value="1" type="checkbox">
      </span>
   </div>
   <label for="cgv">Some text.</label>
</p>

So, the input element #cgv is inside span and div elements. I want to do this by this code but without any results.

$('#submitGuestAccount').click(function () {
        //True if parent is <p> element
        if ($('#cgv').parent().hasClass('checkbox')) {
            $('<span>').insertBefor('#cgv');
            $('</span>').insertAfter('#cgv');

        }
    });

Is anyone can help me with my problem ?

Kind regards

The jQuery API is well documented : http://api.jquery.com/wrap/ .

 $("#cgv").wrap( "<div class=\\"checker\\" id=\\"uniform-cgv\\"><span></span></div>" ); 
 div{border:10px solid red} span{border:10px solid blue} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p class="checkbox"> <input name="cgv" id="cgv" value="1" type="checkbox"> <label for="cgv">Some text.</label> </p> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM