Home > Enterprise >  Selecting text using nth-of-type returns concatenated string
Selecting text using nth-of-type returns concatenated string

Time:12-19

I have the following HTML and I want to select the value "1933".

I tried $('div.mydata dl:nth-of-type(1)').text() but that returns "1933110 m243" where I'd expect "1933". What am I doing wrong? I checked here already.

console.log($('div.mydata dl:nth-of-type(1)').text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div>
    <div >
      Year: Lot size: Total: Cars: Motors:
    </div>
    <div >
      <div>
        <dl>1933</dl>
      </div>
      <div>
        <dl>110 m<sup>2</sup></dl>
      </div>
      <div>
        N.A.
      </div>
      <div>
        <dl>4</dl>
      </div>
      <div>
        <dl>3</dl>
      </div>
    </div>
  </div>
</div>

CodePudding user response:

The selector: $('div.mydata dl:nth-of-type(1)').text() is essentially selecting the first of every <dl> inside of div.mydata.

If you just want the contents of the first <dl> on the page use:

$($('div.mydata div dl').get(0)).text()
  • Related