Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: how can you select texts not surrounded by html tags?

Tags:

jquery

Beer
<br>
Vodka
<br>
rum
<br>
whiskey

how can you select beer ? or rum ? in jquery ? they are not surrounded by any html tags....

like image 964
g2g23g Avatar asked Oct 17 '09 23:10

g2g23g


2 Answers

If you mean that you want to select the text node directly, this is advised against using jQuery. To clarify, getting a wrapped set of text nodes is not a problem, but chaining commands onto a wrapped set of text nodes has unpredictable results or does not work with many of the commands since they expect the wrapped set to contain element nodes.

You can do it by filtering the children of a parent to return only text nodes, i.e. nodeType === 3 but if your question is about performing some manipulation on the text, then get the parent element and manipulate the text contents. For example,

$('#parentElement').html(); // html of parent element

$('#parentElement').text(); // text content of parent element and any descendents

$('#parentElement').contents(); // get all child nodes of parent element

If you wanted to get the text nodes, the following is one way

$('#parentElement').contents().filter(function() { return this.nodeType === 3 });

Or you may want to look at Karl Swedberg's Text Children plugin, which provides various different options too.

EDIT:

In response to your comment, one way to work with the text nodes in a wrapped set is to convert the jQuery object to an array, then work with the array. For example,

// get an array of the immediate childe text nodes
var textArray = $('#parentElement')
                    .contents()
                    .filter(function() { return this.nodeType === 3 })
                    .get();

// alerts the text content of each text node
$.each(textArray, function() {
    alert(this.textContent);
});

// returns an array of the text content of the text nodes
// N.B. Remember the differences in how  different 
// browsers treat whitespace in the DOM
textArray = $.map(textArray, function(e) {
    var text = $.trim(e.textContent.replace(/\n/g, ""));
    return (text)? text : null;
});
like image 115
Russ Cam Avatar answered Oct 05 '22 23:10

Russ Cam


Personally, I'd wrap them in a <span> then you can refer to them more easily. I'm using Russ Cam's filter, so props (and +1) to him

$(document).ready(function(){
 $('body').contents().filter(function(){ return this.nodeType === 3 }).each(function(){
  $(this).wrap('<span class="text"></span>');
 })
})

Then you can just use $('.text') and selectors to access them more easily.

like image 31
Mottie Avatar answered Oct 05 '22 23:10

Mottie