Skip to content Skip to sidebar Skip to footer

Find A Specific Word And Wrap With A Span Tag

i am not sure the best way to go about this. here is the problem. i have a menu (list items) that has an irregular pattern of display. i cant alter the html directly as it is being

Solution 1:

I wrote a simple plugin recently that could accomplish this:

(it no longer exists)

you would use it like this:

var arr = ["about my","locations"];
$.each(arr,function(i,word){
  $(".items").highlightText(word,"bigwords",true)
});

http://jsfiddle.net/4gtmH/23/

Since i'm using a regexp, you could also do it this way:

$(".items").highlightText("about my|locations","bigwords",true)

Also:

I used .items as a class because in my example i gave the ul a class of items. you can supply any selector and it will highlight all text within the element and it's children.

Here's the part of the plugin that does the work, just in case that link goes dead for some reason:

$(this).find("*").andSelf().contents()

// filter to only text nodes that aren't already highlighted
.filter(function () {
    returnthis.nodeType === 3 && $(this).closest("." + hClass).length === 0;
})

// loop through each text node
.each(function () {
    var output;
    output = this.nodeValue.replace(re, "<" + defaultTagName + " class='" + hClass + "'>$1</" + defaultTagName + ">");
    if (output !== this.nodeValue) {
        $(this).wrap("<p></p>").parent()
            .html(output).contents().unwrap();
    }
});

Solution 2:

Have you looked at this jQuery plugin? Haven't used it myself but looks like it does the job pretty easily.

Solution 3:

You can make a jquery selector on all elements and foreach result in the selector set the val with the val replaced with and the data

Post a Comment for "Find A Specific Word And Wrap With A Span Tag"