3

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('br').eq(2).text(), but know that there must be a better way.

    <div id="address">
        Joe Dirt<br>
        PO Box 842<br>
        New York NY 10012<br>
        800-555-5555<br>
        <br>
    </div>

Thanks!

user2062244
  • 113
  • 2
  • 11

6 Answers6

6

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

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

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

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
5

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/

RobertO
  • 2,655
  • 1
  • 20
  • 18
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);
user2736012
  • 3,543
  • 16
  • 13
1

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.

makmonty
  • 465
  • 3
  • 12
0

try this:

var html = $('#address').html();
var arr = html.split('<br>');
var data = arr[2]; //the information that you want
Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
0

I would probably go for this solution to find the text field you want:

  $("div")
  .contents()
  .filter(function() {
    return this.nodeType === 3;
  })[2];

It's presented here : https://stackoverflow.com/a/298758/681538

Why? Because it's delimiter agnostic, and you are really just having a list of text nodes separated with a separator. Since we can get the text nodes with jquery without having to care about what separator you have to adjust to, so why would we?

Community
  • 1
  • 1
Alex
  • 14,104
  • 11
  • 54
  • 77