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
2 Answers
Reset to default 5Assuming that the "lines" are separated by newline characters you can do something like this:
var el = document.getElementById("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
版权声明:本文标题:html - How does one get div content line-by-line with Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745529820a2662007.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论