Michelle
Michelle

Reputation: 2712

Javascript - find all classes from array, grab and return inner text from classes

I have an array of class names that I want to search a page for. Then I'd like to find all those elements, grab the text inside, and append it to a div.

var div = document.createElement('div');
div.innerHTML = 'List of names from this page';
document.body.appendChild(div); 

var classNameArray = ['user', 'username', 'fullname', 'profile-field', 'author', 'screen-name'];

for (var i = 0; i < classNameArray.length; i++) {

  element = classNameArray[i];
  getSuggestedAuthors(element);

  function getSuggestedAuthors(element) {
    var classes = document.getElementsByClassName(element);
    var index;
    for (var index = 0; index < classes.length; index++) {
      var class = classes[index];
      var textInsideClass = class.innerHTML;
      div.appendChild(textInsideClass);
    }
  }
}

When I run this, it gives me:

Uncaught NotFoundError: An attempt was made to reference a Node in a context where it does not exist.

I believe the problem is occuring at var textInsideClass = class.innerHTML, because when I remove that, it simply grabs all the classes and appends them to the div. However, I'd like to only get the text inside the class.

Anyone know how to do this without jQuery? I'm injected this hs through Google Chrome's executeScript injection.

Thanks so much!

Upvotes: 1

Views: 344

Answers (2)

megawac
megawac

Reputation: 11363

If you only need to support chrome then all of the handy methods on the Array.prototype should exist :)

var a = document.createElement('div');
a.innerHTML = 'List of names from this page';
document.body.appendChild(a); 

function getSuggestedAuthors(elements) {
  for (var d = 0; d < elements.length; d++) {
    a.appendChild(document.createTextNode(elements[d].innerText));//append loop items text to a
  }
}
['user', 'username', 'fullname', 'profile-field', 'author', 'screen-name'].map(function(cls) {
  return document.getElementsByClassName(cls);
}).forEach(getSuggestedAuthors);

Upvotes: 1

jameslafferty
jameslafferty

Reputation: 2182

I think your issue is that appendChild only works with nodes. You might be better off just appending to innerHTML using something along the lines of a.innerHTML += f.innerHTML.

You should also be sure to move the getSuggestedAuthors function out of the loop. It works ok as it is, but it's much better form not to declare functions inside a loop.

Upvotes: 3

Related Questions