Clain Dsilva
Clain Dsilva

Reputation: 1651

Identify a text using jquery and warp it insde a container

Here is the code

<form method="get" name="form_delivery">

  Please select country for delivery<br>

  <select name="deliverymethod">
    <option value="0" selected="selected">Select country / region</option>
    <option value="1">UK (incl. Northern Ireland)</option>
    <option value="8">Australia</option>
    <option value="9">New Zealand</option>
  </select>

</form>

I need to identify the text "Please select country for delivery" and wrap it around the container like a "span" and replace the wrapped text

<form method="get" name="form_delivery">

   <span>Please select country for delivery</span><br>

This code is generated by an automated server, I only have access to HTML Template hence Jquery is the only option for making modifications on the fly.

Any Idea's?

Upvotes: 0

Views: 131

Answers (3)

George
George

Reputation: 36794

You can use contents() to get the text nodes as well as the HTML elements using jQuery. You can then filter out the text nodes, using .filter() (which might be unnecessary, depending on your potential markup) and then get what I'm assuming will always be the first text node, using .eq().

From there we can wrap this text node in a <span> using .wrap(), traverse to this new <span>, and prepend it to our form:

var $form = $('form[name=form_delivery]')
$form.contents().filter(function(){
    return this.nodeType == 3;
}).eq(0).wrapAll('<span></span>').closest('span').prependTo($form);

JSFiddle

Upvotes: 1

rdubya
rdubya

Reputation: 2916

If you know that the text is the first part of the form, you can use $($('form').get(0).childNodes[0]).wrap('<span>');.

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382187

Two solutions here :

1 : If you don't have any binding on other elements of the form, you may simply do a replace of the HTML :

$('form').html(function(_,h){
     var t = "Please select country for delivery";
     return h.replace(t, '<span>'+t+'</span>');
});

2 : If you have bindings, you can't do that as it would delete all elements, you need to do it cleanly, not modifying other elements. You may use a library for that like my own groumf :

Groumf.replaceTextWithHTMLInHTML(document.body, t, function(s){
    return '<span>'+t+'</span>'
});

Upvotes: 1

Related Questions