2

I have a form that I am working with that has a bit of unwrapped text. I have no access to the HTML file so the only way I'm going to be able to select it is through Jquery (so I've been told). This is what the HTML looks like:

<div class="input-entry">
<div class="input-area">
<div class="input-checkbox">
<input type="checkbox" name="accept"> 
I Accept
</div>
</div>
</div>

I need to select the 'I Accept' to wrap a <label> around it. I don't know very much about jQuery but I did try this:

$("div.input-area:contains('I Accept')").wrap("<label for='accept'></label>");

Which I thought at first glance would work but I miss interpreted what the :contains selector does.

Is it possible to simply wrap it using Jquery?

user2596635
  • 381
  • 1
  • 5
  • 17

4 Answers4

4

Yes it is possible, you need to get the content and then filter by node type (nodeType '3' is a text node):

$("div.input-checkbox:contains('I Accept')").contents().filter(function(){
    return this.nodeType === 3;
}).wrap("<label for='accept'></label>");

I have also changed your initial selector.

http://jsfiddle.net/mb1yg111/

Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
  • This fiddle is no longer working. It's wrapping the div. I'm trying to solve this same problem. Trying to wrap unwrapped text. – KingRichard May 27 '15 at 21:08
  • @RichardN This fiddle is working for me, could you tell me which browser you are using? That may be the problem. Also, I would gladly help you if you give me some code to bites on! – Karl-André Gagnon May 28 '15 at 00:31
  • This is the output I get: [jsfiddle](http://jsfiddle.net/ye3beygh/1/). Based on the script, I'm guessing it should just wrap the text itself, not the parent > parent div. I got mine to work, just not using the content search. I posted it up here: [jsfiddle2](http://jsfiddle.net/s45gmz4u/1/) – KingRichard May 28 '15 at 16:11
2

Maybe it's not pretty, but you can achieve it with this:

$(".input-checkbox").html(
     $(".input-checkbox").html().replace(
         'I Accept',
         "<label for='accept'>I Accept</label>"));

JSFiddle demo: http://jsfiddle.net/lparcerisa/h98egbpv/

lpg
  • 4,897
  • 1
  • 16
  • 16
0

Node you want to select is text node. It's bit inconvinient, but possible. You can find detailed description in this question: How do I select text nodes with jQuery?

In short:

$(elem)
  .contents()
  .filter(function() {
    return this.nodeType === 3; //Node.TEXT_NODE
  });
Community
  • 1
  • 1
DzikiMarian
  • 423
  • 3
  • 14
0

This can be achieved with following. You remove all the child node and then pick up the remaining text.

$('.input-checkbox').clone().children().remove().end().text()

JSFiddle http://jsfiddle.net/ux1bg1w9/1/

Vishwanath
  • 6,284
  • 4
  • 38
  • 57