Check string and only wrap words NOT already wrapped?

I hve the following HTML string:

<span class="class1">Hello</span> my <span class="class1">name</span> is Mads.

Is it possible to detect the words 'my', 'is' and 'Mads' and wrap those words in a string who is not already part of a span tag?

So it becomes

<span class="class1">Hello</span> <span class="class1">my</span> <span class="class1">name</span> <span class="class1">is</span> <span class="class1">Mads.</span>

Thanks in advance.

Upvotes: 1

Views: 1150

Answers (4)

Right,

I have cracked it - although it may not be the prettiest code you guys have seen.

The html spans are updated on -blur event (when you click outside the div editable field).

a link to jsfiddle example!

Upvotes: 0

Robert
Robert

Reputation: 8767

Try the following:

HTML:

<div id="parent">
    <span class="class1">Hello</span> my <span class="class1">name</span> is Mads.
</div>

jQuery:

$(document).ready(function(){
    $('#parent').contents().filter(function() {
        return this.nodeName == '#text';
    }).replaceWith(function(){
        return this.nodeValue.replace(/([a-zA-Z0-9_-]+)/g, '<span class="class1">$1</span>');
    });
});

Demo: http://jsfiddle.net/CDe5j/

The code above takes the #parent object and then uses contents() to get the children within. It then applies the filter() method, which tests the supplied selector against each element and all of the elements matching the selector will be selected. Once only the text elements, non-spans, are selected, the replaceWith() method is used to ensure that each individual word is wrapped as a span element, via a regex for all alpha-numberical characters, underscore, and hyphen. You can view additional information on Regular Expresions here.

Upvotes: 2

Šime Vidas
Šime Vidas

Reputation: 185883

First, parse the HTML string into the DOM by putting it into a DIV element, like so:

<div id="wrap">
   <span class="class1">Hello</span> my <span class="class1">name</span> is Mads.
</div>

Now, execute this code:

var $wrap = $( '#wrap' );

$wrap.contents().filter(function () {
    return this.nodeType === 3 && $.trim( this.data );
}).replaceWith(function () {
    return this.data.replace( /(\w+)/g, '<span class="class1">$1</span>' );
});

After the above code ran, you can retrieve the resulting string like so:

var result = $wrap.html();

Live demo: http://jsfiddle.net/Rhpaa/1/

I'm using /(\w+)/ to match a word. I'm not sure how reliable it is. If it doesn't work reliably, try to find a more reliable word-matching regular expression on SO.

Upvotes: 1

Eivind Eidheim Elseth
Eivind Eidheim Elseth

Reputation: 2354

If you get the parent element you can use the jQuery objects text() function to get the text. You can the use split(" ") to create an Array and iterate over it to wrap each token in a tag.

Upvotes: 1

Related Questions