2

I need to process the content of a <div> line-by-line. A shortened piece of it looks like this:

<div id='aoeu'>
    Ammonium NH%4^+ <br />
    Copper(I) Cu^+ <br />
    Gold(I) Au^+ <br />
    Rubidium Rb^+ <br />
    Acetone CH%3COCH%3 <br />
    Glycerin C%3H%5(OH)%3 <br />
</div>

I need to work with each line individually with Javascript.

RandomDuck.NET
  • 490
  • 5
  • 17

2 Answers2

5

Assuming that the "lines" are separated by newline characters you can do something like this:

​var el = document.get​ElementById("aoeu"),
    content = el.innerHTML.replace(/  |^\s+|\s+$/g,""),
    lines = content.split("\n");

That is, get the innerHTML of the element, remove the leading and trailing whitespace, and then split on the newline character.

Demo: http://jsfiddle.net/RG2WT/

EDIT: Now that you've added <br> elements (though I'd remove the trailing one):

var el = document.getElementById("aoeu"),
    content = el.innerHTML.replace(/^\s+|\s*(<br *\/?>)?\s*$/g,""),
    lines = content.split(/\s*<br ?\/?>\s*/);

That is, get the innerHTML, remove leading and traling whitespace and any trailing <br> element, and then split on each remaining <br> element plus the whitespace around it.

Demo: http://jsfiddle.net/RG2WT/3/

Either way lines will be an array with each element being one of your lines. Either way I'm removing leading and trailing white space so that, e.g., the first item will be "Ammonium NH%4^+" not " Ammonium NH%4^+ ".

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
1

I would first get the innerHTML and assign to a var. Take the var and split on br's to get an array, which you can do whatever you need with.

var contents = document.getElementById("aoeu").innerHTML;
var lines = contents.split("<br />");
// Do whatever you want with lines
The Awnry Bear
  • 4,599
  • 3
  • 29
  • 33