1

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?

rebello95
  • 8,486
  • 5
  • 44
  • 65
Martin
  • 795
  • 1
  • 12
  • 31

2 Answers2

2

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>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • @Martin see also [text nodes](http://stackoverflow.com/questions/17195868/what-is-a-text-node-its-uses-document-createtextnode) – bruchowski Oct 16 '14 at 03:09
  • That works well, but it only targets the first. I actually have 5 or so that I need to target. – Martin Oct 16 '14 at 03:12
1

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>" );
artm
  • 8,554
  • 3
  • 26
  • 43