SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Feb 2006
    Posts
    25
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Changing id to class to validate

    I'm a CSS guy - not a Javascript guy. I go for validation. But of course, you can't use more than one ID per page. When I'm using a js code more than once on a page, how can I convert the ID to a class?

    Code JavaScript:
    function togglevis(target)
         {
             obj=document.getElementById(target);
             obj.style.display=( (obj.style.display=='none') ? '' : 'none');
         }
     
     
     
    function showHide(shID) {
    	if (document.getElementById(shID)) {
    		if (document.getElementById(shID+'-show').style.display != 'none') {
    			document.getElementById(shID+'-show').style.display = 'none';
    			document.getElementById(shID).style.display = 'block';
    		}
    		else {
    			document.getElementById(shID+'-show').style.display = 'inline';
    			document.getElementById(shID).style.display = 'none';
    		}
    	}
    }

    I've tried to modify the above codes to work with classes, but apparently I suck. Help?

  2. #2
    SitePoint Wizard
    Join Date
    Nov 2004
    Location
    Nelson BC
    Posts
    2,310
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Where possible, pass the element itself to your functions rather than the id, thereby doing away with the need for most ids.
    Code:
    function togglevis(obj)
         {
             obj.style.display=( (obj.style.display=='none') ? '' : 'none');
         } 
    
    <div onclick="togglevis(this);">...
    Sometimes you don't want to operate on the thing that was clicked on, but something that's in a predictable position in your html:

    Code:
    function showHideUL(obj) {
      if (obj.style.display == "none") {
        obj.style.display = "";
      } else {
        obj.style.display = "none";
      }
    }
    
    <li>
      <a href="#" onclick="showHideUL(this.parentNode.getElementsByTagName('ul')[0]);">something</a>
      <ul>.....</ul>
    </li>
    Maybe you could convert your showHide function to be like my second example? If not show some of your html elements and we can rework it.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •