Welcome to WebmasterWorld Guest from 54.166.33.25

Forum Moderators: open

accessing <p> tags after <a> in html document

accessing a set of <p> tags after <a> tag using getElementsByTagName('a')

   
2:03 am on Dec 16, 2007 (gmt 0)

5+ Year Member



Hi,

I need some help in accessing a set of <p> tags after <a> tag using getElementsByTagName('a'); I want to access the <p> tags after <a name="PAGE2">, <a name="PAGE3"> etc.

This is what the HTML body has:
<p class="verdana">First Paragraph </p>
<p class="verdana">Second Paragraph </p>

<a name="PAGE2"></a>
<p class="verdana">Six Paragraph </p>
<p class="verdana">Seven Paragraph </p>
<a name="PAGE3"></a>
<p class="verdana">Ten Paragraph </p>
<p class="verdana">Eleven Paragraph </p>
===
var aList = document.getElementsByTagName('a');
for(var i=0; i<aList.length; i++){
if(aList[i].name.indexOf('PAGE')!=-1){
//alert(aList[i].name);
var nextP = document.getElementsByTagName("a")[i].nextSibling;//getting undefined here

Can you suggest any way of doing this?

Thanks,

6:08 pm on Dec 16, 2007 (gmt 0)

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



In your example, I think the "nextSibling" is a text node containing the newline character... the newline between your <a> and <p> nodes.

My suggestion would be to use the YAHOO UI Library's DOM Utility for this. It has a method that returns only the "element" siblings. For example:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
</head>
<body>
<p class="verdana">First Paragraph </p>
<p class="verdana">Second Paragraph </p>
<a name="PAGE2"></a>
<p class="verdana">Six Paragraph </p>
<p class="verdana">Seven Paragraph </p>
<a name="PAGE3"></a>
<p class="verdana">Ten Paragraph </p>
<p class="verdana">Eleven Paragraph </p>
<script type="text/javascript" src="http://yui.yahooapis.com/2.4.0/build/yahoo-dom-event/yahoo-dom-event.js" ></script>
<script type="text/javascript">
YAHOO.util.Event.on(window, 'load', function() {
var aList = document.getElementsByTagName('a');
for (var i = 0; i < aList.length; i++) {
if (aList[i].name.indexOf('PAGE')!= -1) {
var str = aList[i].name + "\n";
for (var sibling = YAHOO.util.Dom.getNextSibling(aList[i]); null!= sibling && sibling.tagName == "P"; sibling = YAHOO.util.Dom.getNextSibling(sibling) ) {
str += "\n" + sibling.innerHTML + "\n";
}
alert(str);
}
}
});
</script>
</body>
</html>

3:02 pm on Dec 17, 2007 (gmt 0)

10+ Year Member



Fotiman is probably correct about the textNode or EmptySpace.

Here is a simple example of how to move to the nextSibling and check to see if it is a TextNode or nodeType 3.

function myFunction() {
vSibling = document.getElementById("first").nextSibling
while (vSibling.nodeType==3) { // Fix for Mozilla/FireFox
vSibling = vSibling.nextSibling;
};
 

Featured Threads

My Threads

Hot Threads This Week

Hot Threads This Month