Inside JavaScript

The nextSibling and previousSibling Properties

The nextSibling and previousSibling properties are W3C DOM properties that are useful when navigating an HTML document as a node tree, enabling you to navigate between sibling nodes (that is, nodes at the same level in the document). You can see the support for these properties in Table 5.35.

Table 5.35. The nextSibling and previousSibling Properties

Property

NS2

NS3

NS4

NS6

IE3a

IE3b

IE4

IE5

IE5.5

IE6

nextSibling

     

x

     

x

x

x

 

Read-only

 

Type: Object

previousSibling

   

x

     

x

x

x

 
 

Read-only

 

Type: Object

Tip

Bear in mind, as discussed in Chapter 4, that the Internet Explorer and Netscape Navigator can treat whitespace text nodes differently, which makes a difference when navigating node by node.

We've already seen the nextSibling property at work in the preceding chapter; this property returns the next node at the same level as the current node, letting us navigate through an HTML document like this:

(Listing 04-12.html on the web site)

<HTML> <HEAD> <TITLE> Accessing HTML Elements </TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- function getText() { if(navigator.appName == "Netscape") { var body1 = document.getElementById("body") var h1 = body1.childNodes[1] var form1 = h1.nextSibling.nextSibling var text1 = form1.childNodes[1] alert(text1.value) } if (navigator.appName == "Microsoft Internet Explorer") { var body1 = document.getElementById("body") var h1 = body1.childNodes[0] var form1 = h1.nextSibling var text1 = form1.childNodes[0] alert(text1.value) } } // --> </SCRIPT> </HEAD> <BODY ID="body"> <H1>Accessing HTML Elements</H1> <FORM NAME="form1"> <INPUT TYPE="TEXT" NAME="text1" ID="text1"> <INPUT TYPE="BUTTON" VALUE="Click Me!" ONCLICK="getText()"> </FORM> </BODY> </HTML>

Here's an example putting the previousSibling property to work; in this case, I'm navigating through the elements in a form, starting at the button and ending up with the text field, using previousSibling :

(Listing 05-16.html on the web site)

<HTML> <HEAD> <TITLE> Accessing HTML Elements </TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- function getText() { if(navigator.appName == "Netscape") { var button1 = document.getElementById("button1") var text1 = button1.previousSibling.previousSibling alert(text1.value) } if (navigator.appName == "Microsoft Internet Explorer") { var button1 = document.getElementById("button1") var text1 = button1.previousSibling.previousSibling alert(text1.value) } } // --> </SCRIPT> </HEAD> <BODY ID="body"> <H1>Accessing HTML Elements</H1> <FORM NAME="form1"> <INPUT TYPE="TEXT" NAME="text1" ID="text1"> <INPUT TYPE="BUTTON" VALUE="Click Me!" ID="button1" ONCLICK="getText()"> </FORM> </BODY> </HTML>

Категории