I am trying to write a Javascript that sorts some paragraphs. Here’s a small snippit of the HTML that I am sorting:
<p>Brown, John, 2010, <a href="#">Link</a></p>
<p>Bush, C.A., 2010, <a href="#">Link</a>: More info.</p>
<p><br></p>
<h3><a name="c">C</a></h3>
<p>Caine, J.S., and Minor, S.A., 2010, <a href="#">Link</a>: More</p>
This Javascript is looking for the entries that contain “2010” (which are 3 out of the 4 paragraphs):
var paras = document.getElementsByTagName("p");
alert( paras.length ); // 4, which is what I expect!
for( i=0; i < paras.length ; i++ ) {
var node0_text = paras[i].childNodes[0].nodeValue;
if ( node0_text.indexOf('2010') ) {
alert( node0_text ); // not returning everything that I expect it to.
};
}
When I run this the first 2 entries (“Brown” and “Bush”) pop up in the alert box just as I expect they would. Then the script seems to die. It does not display the third (“Caine”) entry. What went wrong here? Thanks for any input.
A link to it: http://jsfiddle.net/Jrmy/6MP2W/5/
The “Caine” entry is in the fourth paragraph. The script fails because the third paragraph has no text.
This is the third paragraph:
The text is
nullso theifstatement gets an exception for trying to access.indexOf().(edit — a good comment points out that it’s the
<br>tag being checked for a value, but that’s null too.)