Node text search
Here's how to select text nodes using jQuery:
var x = $('div') .contents() .filter(function() { return this.nodeType == 3; //return this.nodeType == Node.TEXT_NODE; this works unless using IE 7 }); In your example, x will contain βoneβ at index 0 and βthreeβ at index 1. As Keith Russo said, you cannot just grab this text, but if you know this will be the last, you can get it something like this:
var elemThree = x[x.length-1]; You can also add a strong tag as follows:
$(x[x.length-1]).wrap("<strong></strong>"); This discusses the selection of text nodes using jQuery (my first piece of code).
Is there a reason why you cannot wrap three in any html element when creating markup? It is actually impossible to take some random word from the text and wrap it - unless you know that it will always be the absolute last word in the div. If so, you can do this to get the word:
var txt = $(div).text(); var txtArr = txt.split(); var wordToWrap = txtArr[txtArr.length - 1]; I'm not sure that you can easily do this with direct jQuery, unless you can wrap this word in another tag when writing it. You can resort to regular expressions, for example:
function wrapWithTag(tagname, element, text) { var html = element.html(); var rx = new RegExp('(' + text + ')', "gi"); element.html(html.replace(rx, '<' + tagname + '>$1</' + tagname + '>')); } $(function(){ wrapWithTag('strong', $('div'), 'three'); }); The regex needs some tweaking if you're trying to match text in different places inside an element.
Check out this jQuery highlighting plugin: http://tinyurl.com/6rk6ae
It may not do exactly what you want, but the source contains good examples of working with text nodes and effective modification of the DOM around them.
CSS cannot select text nodes
jQuery uses css3 selectors that select only elements. To get the desired effect, you need to do the following:
var div = $('find the div')[0]; var txtNode = div.lastChild var str = document.createElement('strong') str.appendChild(txtNode) //removes the text node from the dom. div.appendChild(str) If this is not about the last word, but about the pure contents of the div, try this:
var chld=$('div').children().clone(); $(div).children().remove(); //now do what You want with the text, eg. $(div).html('<strong>'+$(div).text()+'</strong>'); //or something like that :) $(div).prepend(chld); //This is a bottleneck, cause You have to know that //all the text was after all the markup, but it refers to Your example.