Skip to content Skip to sidebar Skip to footer

Selecting Text Between

Is it possible to select text between tags? I am working with the preformatted code below trying to select this data: New York, NY 10012 I've played around with $('#address').find

Solution 1:

Retrieve the HTML for the div and split on the br tag:

$.trim($("#address").html().split("<br>")[2]);

JS Fiddle: http://jsfiddle.net/KQgu5/


Solution 2:

Instead of selecting the text based on the html you can use the DOM and pick out the appropriate TextNode using the childNodes array.

Since the Nodes are counted starting at 0:

address.childNodes[0] # "Joe Dirt"
address.childNodes[1] #   br element
address.childNodes[2] # "PO Box 842"
address.childNodes[3] #   br element
address.childNodes[4] # "New York NY 10012"
address.childNodes[5] #   br element
address.childNodes[6] # "800-555-5555"
address.childNodes[7] #   br element

Example code:

var address = document.getElementById ("address");
alert(address.childNodes[4].nodeValue);

http://jsfiddle.net/78evc/


Solution 3:

var vals = $("#address > br").map(function(i, br) {
    return $.trim(br.previousSibling.data);
}).toArray();

Since the text always appears before a <br> element, you can select the brs and map the .previousSibling.data of each to an Array.

This also doesn't suffer from the possibility of HTML rendering being a little different in different browsers, which you can get with HTML parsing approaches.


If you just need the one value, then do this:

var txt = $.trim($("#address > br")[2].previousSibling.data);

Solution 4:

How about this:

var line = $("#address").html().split(/<br *\/?>/i)[2];

I know it's not "selecting" the line, but as there's no other way with or without jQuery (your solution didn't work for me out-of-the-box), I think it can be a good approach.

Please note it's allowing different ways of writing the <br> tag.


Solution 5:

try this:

var html = $('#address').html();
var arr = html.split('<br>');
var data = arr[2]; //the information that you want

Post a Comment for "Selecting Text Between
"