Monday, November 29, 2010

Sorting Elements by ID in javascript

So I have, say, a list of members that are sorted out on the page in sections, each section has its own id#. By default I want to display all of the IDs, but when someone selects a radio button I want only one section (id) to be shown.

Solution 1

First,

dom element id's can not be numbers (some frameworks will no work properly because of this)

that aside,

You want a list of all the id's in a javascript array, populate it however you want ..

var ids = new Array('id1','id2','id3','id4');
var current = 'id1'; // Currently shown member id

function switch($id) {
hide = new Array();
len = ids.length;
for(x=0; x< ele =" document.getElementById($id);" display =" '';" len =" arguments.length;" x="0;" ele="document.getElementById(arguments[x]);" display="none" in="" your="" radio="" buttons="">

input onclick="switch(this.value)" value="" type="radio"

Solution 2

If you know the ID of each section, and depending on the structure of your HTML tags, you can can loop through all the main tags within a section ( by #id ) and hide all except for the one that referred to by the radio butotn.

input onclick="single( 'item3', 'section1' )" value="" type="radio"

function single( id, sec )
{
var section = document.getElementById( sec );
var items = section.getElementsByTagName( 'li' );

for( var i=0; i < items.length ; i++ ) { items[i].style.display = ( items[i].id === id ) ? '' : 'none'; } }

No comments: