mayorbyrne
mayorbyrne

Reputation: 507

Cheerio not traversing correctly?

I have the following code:

var cheerio = require('cheerio');
var html = "<div> <h3>Header 1</h3> <h3>Header 2</h3></div> <h3>Header 3</h3>";
var $ = cheerio.load(html);

console.log($('h3').length); // 3

var input = $('h3').first();

console.log(input.text()); // Header 1

input = input.next();

console.log(input.text()); // Header 2

input = input.next();

console.log(input.length); // 0
console.log(input.text()); // ''

Granted, the HTML code isn't the best in the west, but I'm wondering why the length prints correctly, the first two H3 blocks print correctly, and then when I call next() for the third header, it doesn't exist. However, if I

console.log($('h3').last().text())

it prints out "Header 3". I just can't figure out how to traverse to it from the previous h3.

Hopefully this makes sense, but I can't tell if this is cheerio by design, or if it's misbehaving. If someone could please explain to me why this bit of code doesn't work how I'm expecting it to, I'd appreciate it.

Upvotes: 1

Views: 797

Answers (1)

Nick Tomlin
Nick Tomlin

Reputation: 29231

The first call to next works because you are grabbing the first h3 element (thereby limiting your collection of items to 1 element), and looking for a sibling h3. The second call is undefined since Header 2 does not have an additional sibling h3.

<div> 
  <!-- siblings, yay! -->
  <h3>Header 1</h3> <!-- var input = $('h3').first(); -->
  <h3>Header 2</h3> <!-- input.next() -->
</div> 

<!-- all alone :( -->
<h3>Header 3</h3>

If you want to perform manipulations over the all of your h3 elements, use jQuery's collection methods:

var inputs = $('h3');

inputs.each(function () {
  console.log($(this).text());
});

// Header 1
// Header 2
// Header 3

console.log(inputs.eq(1).text());
// Header 2
console.log(inputs.eq(0).text());
// Header 1

Upvotes: 3

Related Questions