admin管理员组

文章数量:1428622

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.

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.

Share Improve this question edited Jul 20, 2012 at 3:41 RandomDuck.NET asked Jul 20, 2012 at 3:36 RandomDuck.NETRandomDuck.NET 4905 silver badges17 bronze badges 2
  • Are the "lines" separated by newline characters (\n)? Because if you want them to actually appear on separate lines in the browser you need to put <br> between. – nnnnnn Commented Jul 20, 2012 at 3:38
  • Ah yes, nice catch. I'll get on that... – RandomDuck.NET Commented Jul 20, 2012 at 3:41
Add a ment  | 

2 Answers 2

Reset to default 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/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/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^+ ".

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

本文标签: htmlHow does one get div content linebyline with JavascriptStack Overflow