简体   繁体   中英

jQuery wrap label around plain text

I want to wrap a label around plain text that doesn't have something to easily target it.

For example, this:

<div class="checbox">
    <input type="checkbox">
     some text
</div>

Should become:

<div class="checbox">
    <input type="checkbox">
     <label>some text</label>
</div>

If I could modify the HTML this would be trivial, but I cannot.

With jQuery how could I wrap this "some text" with a label?

If the html structure is constant then, you want to wrap the last child of the div with class checkbox

 $($('.checbox')[0].lastChild).wrap('<label />') 
 label { color: red } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="checbox"> <input type="checkbox" /> some text </div> 


If you have multiple elements like this then

 $('.checbox').each(function(){ $(this.lastChild).wrap('<label />') }) 
 label { color: red } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="checbox"> <input type="checkbox" /> some text </div> <div class="checbox"> <input type="checkbox" /> some text 2 </div> 

See http://jsfiddle.net/zxhcb6sw/

It'll wrap all text nodes inside the div:

$( ".checbox" )
.contents()
.filter(function() {
    return this.nodeType === 3;
})
.wrap( "<label></label>" );

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