chatycat99
chatycat99

Reputation: 107

Reading an HTML NodeList into an array

The sample code below currently gets an HTML page, and tries to read it into an array. The AJAX is working perfectly, and I can get a nodelist object successfully. Is it possible to somehow read this page into an array and not one singular object? Eventually I need to pull out every single member of this array individually as I am attempting in the for loop below:

$.ajax({
 url: "/thePageToScrape.html",
 dataType: 'text',
 success: function(data) {
      var elements = $("<div>").html(data)[0].getElementsByTagName("body");
      for(var i = 0; i < elements.length; i++) {
           var theText = elements.firstChild.nodeValue;
           // Do something here
      }
 }
});

Upvotes: 0

Views: 242

Answers (3)

MaxPRafferty
MaxPRafferty

Reputation: 4977

If you are using JQuery, you can get a list of each node immediately below the body with

var elements = $(data).children("body").children();

or every node with

var elements = $(data).children("body *");

you can then loop over them with

$.each(elements, function(index, value) {
  var text = this.text()
//..do something with text
});

Upvotes: 1

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

If all you want, like you stated in your comment, is to turn the NodeList into an array:

elements = Array.prototype.slice.apply(elements);

That's all, really.

Upvotes: 2

A. Wolff
A. Wolff

Reputation: 74420

Looks like $.parseHTML() method do exactly what you want:

Description: Parses a string into an array of DOM nodes.

var arrElements = $.parseHTML(data);

Upvotes: 1

Related Questions