Results 1 to 3 of 3

Thread: Assign a classname to <li> only if it has child

  1. #1
    Join Date
    Jan 2006
    Location
    Ft. Smith, AR
    Posts
    795
    Thanks
    57
    Thanked 129 Times in 116 Posts

    Default Assign a classname to <li> only if it has child

    I was wondering if this is possible with js?

    Say you've got several nested <ul> elements, and you'd like to use a small bit of js to assign the "parent" <li>'s a special classname...

    HTML Code:
    <ul>
    <li>Child</li>
    <li>Child</li>
    <li>Parent
      <ul>
        <li>Grandchild</li>
        <li>Grandchild</li>
      </ul>
    </li>
    <li>Child</li>
    </ul>
    So how could you go about getting js to autmatically assign the special classname to the "Parent" <li> shown above?
    Last edited by TheJoshMan; 01-07-2009 at 09:43 AM.
    --------------------------------------------------
    Reviews, Interviews, Tutorials, and STUFF
    --------------------------------------------------
    Home of the SexyBookmarks WordPress plugin

  2. #2
    Join Date
    Sep 2005
    Location
    India
    Posts
    1,627
    Thanks
    6
    Thanked 107 Times in 107 Posts

    Default

    The following function should be able to do this,

    Code:
    function addClassToLis() {
        var uls = document.body.getElementsByTagName('ul');
        for (var i = 0; i < uls.length; ++i) {
            var lis = uls[i].getElementsByTagName('li');
            for (var j = 0; j < lis.length; ++j) {
                var chuls = lis[j].getElementsByTagName('ul');
                if (chuls.length > 0) {
                    lis[j].className = "parent";
                }
            }
        }
    }
    Hope this helps.

  3. The Following User Says Thank You to codeexploiter For This Useful Post:

    TheJoshMan (01-07-2009)

  4. #3
    Join Date
    Jan 2006
    Location
    Ft. Smith, AR
    Posts
    795
    Thanks
    57
    Thanked 129 Times in 116 Posts

    Default

    perfect! Thank you very much!
    --------------------------------------------------
    Reviews, Interviews, Tutorials, and STUFF
    --------------------------------------------------
    Home of the SexyBookmarks WordPress plugin

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
  •