简体   繁体   中英

How do I get the previous <div> element text using jQuery()?

How do I get the last previous div element using jQuery()? The ID of the element after the one I'm looking for is 'A0.R0.Work Phone #'.

Here is what the HTML looks like...

<td class="fl flu">
    <div id="ap_cv_valid" style="float: left; display: block; ">
        V
    </div>
    <div style="float:right">
        Primary Phone #
    </div>
</td>
<td class="fv fvu" style="padding-left: 6px; cursor: text;" id="A0.R0.Work Phone #"></td>

What I'm using now is...

var location = 'td[id^="A0.R0.Work"]'
var last = jQuery(location).prev(function(){
    jQuery('div:last').text()
});

I'm looking for last to contain the text string 'Primary Phone #' only.

Got any ideas?

Thanks.

Is this what you want?

HTML:

​<table>
  <td class="fl flu">
    <div id="ap_cv_valid" style="float: left; display: block; ">
    V
    </div>
    <div style="float:right">
      Primary Phone #
    </div>
  </td>
  <td class="fv fvu" style="padding-left: 6px; cursor: text;" id="A0.R0.Work">Phone #</td>
</table>

JS:

var last = $('td#A0\\.R0\\.Work').prev().find('div:last');
console.log(last.text());

`​​​​​​​​​​Demo: http://jsfiddle.net/DkB9t/

Note that it's bad if the element id contains spaces, and it's better not to include "." as well. If you need to have either space or "." in you id, you'll have to escape it with "\\\\"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM