Web Analytics Made Easy -
StatCounter how do you capture array of sibling elements? - CodingForum

Announcement

Collapse
No announcement yet.

how do you capture array of sibling elements?

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • how do you capture array of sibling elements?

    i have a function that's supposed to change the class of an <li> to "open" onclick and change all of it's sibling <li>s classes to "shut". However, i'm not capturing the siblings correctly and I'm not sure what needs to be changed. Here's the code...

    Code:
    <script type="text/javascript" language="javacript">
    	function toggle() {
    		this.className='open';
    		var items=this.parentNode.getElementsByTagName('li');
    		for(var i=0,len=items.length;i<len;i++) {
    			if(items[i]!=this) items[i].className='shut';
    		}
    	}
    </script>
    
    <div>
    	<ul>
    		<li class="open" onclick="toggle()">One<a href="x">This is a test</a></li>
    		<li class="shut" onclick="toggle()">Two<a href="x">This is a test</a></li>
    		<li class="shut" onclick="toggle()">Three<a href="x">This is a test</a></li>
    	</ul>
    </div>
    ...and this seems to be the offending line as it's not returning a value...

    Code:
    var items=this.parentNode.getElementsByTagName('li');
    i've never used parentNode before so maybe the syntax is a bit off?

  • #2
    *solved*

    solved it!

    Code:
    <script type="text/javascript">
    	// <![CDATA[
    		function toggle(which){
    			which.className = "open";
    			var items = which.parentNode.getElementsByTagName("LI");
    			
    			for(var i = 0; i < items.length; i++){
    				if(which != items[i])
    					items[i].className = "shut";
    			}
    		}
    	// ]]>
    </script>
    
    <div>
    	<ul>
    		<li class="open" onclick="toggle(this)">One<a href="#">This is a test</a></li>
    		<li class="shut" onclick="toggle(this)">Two<a href="#">This is a test</a></li>
    		<li class="shut" onclick="toggle(this)">Three<a href="#">This is a test</a></li>
    	</ul>
    </div>

    Comment

    Working...
    X