Search code examples
javascriptjquerymls

Get text before the last br in div jquery


Hi Guys i have this in html

<div class="flexmls_connect__sr_address">
  <div class="flexmls_connect__ld_price">$9,000,000</div>
  Km. 16.5 Carr. Barra de Navidad, Villa Armonia Estate
  <br>
  Puerto Vallarta, JA
  <br>MLS# 11187
  <br>//NEED THIS NUMBER---- >5 beds &nbsp;|&nbsp; //AND THIS NUMBER---- >8 baths &nbsp;|&nbsp; 11836 sqft
  <br>
</div>

and this in jquery

    var baths = $(res).find('.flexmls_connect__sr_address').before('br').last().contents().filter(function() {
        return this.nodeType == 3;
    }).text();

I need obtain the beds and baths, and for clearify not is my html code i obtain from a very old API and i cant change the HTML, i neee that values with only jquery or javascript. not neccesary with my answer all methos are welcome i only try many of theme and the last is get text before last tag br but any help is great, thanks :D


Solution

  • before() is a dom insertion method. Can do something like the following

    var specs = $('.flexmls_connect__sr_address').contents().filter(function() {
        return this.nodeType == 3 && $(this).text().indexOf('beds')>-1;
    }).text().split('|').reduce(function(a,c){
        if(c.indexOf('beds')>-1){
            a.beds = /\d+/.exec(c)[0]
        }else if(c.indexOf('baths')>-1){
            a.baths = /\d+/.exec(c)[0]
        }
        return a
    },{});
    
    console.log(specs);
    console.log('Property has ', specs.baths, ' baths and ', specs.beds, ' beds');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="flexmls_connect__sr_address">
      <div class="flexmls_connect__ld_price">$9,000,000</div>
      Km. 16.5 Carr. Barra de Navidad, Villa Armonia Estate
      <br>
      Puerto Vallarta, JA
      <br>MLS# 11187
      <br>5 beds &nbsp;|&nbsp; 8 baths &nbsp;|&nbsp; 11836 sqft
      <br>
    </div>