Get parent element without jQuery

I have all the scripts I need in place, but just need to complete this function, and without using a JS library:


function get_main_parent (elem) {

     //get the parent of the element (elem) that has the 'main-class' class and add a class to the first <div> in that parent element

}

The below will have an element triggered by click or focus, and that element will be passed into the above function (I only need to complete the function):

(1) clicking the <a> link


<div class="main-class">
  <div>

   <span class='anything'>
     <a id='this-element' href="">Click</a>
   </span>

  </div>
</div>

(2) focusing in an input box


<div class="main-class">
  <div>

    <input type="text" />

  </div>
</div>

All of them then add the class, so example 2 would then become:


<div class="main-class">
  <div class="the-new-class-added">

    <input type="text" />

  </div>
</div>

…basically the event could be triggered anywhere, and any number of elements deep. The function just needs to receive an element and go up the DOM tree to find the div with ‘main-class’ as the class and then step forward one to find the first <div> and add a class to that.

I’m sure there’s a better way to explain this. Thanks.

Perhaps with this pseudo code:


(function () {
    "use strict";
    
    // hasClass, addClass and removeClass from http://snipplr.com/view/67176/class-handling-functions/

    function hasClass(ele, cls) {
        return ele.className.match(new RegExp('(\\\\s|^)' + cls + '(\\\\s|$)'));
    }

    function addClass(ele, cls) {
        if (!hasClass(ele, cls)) {
            ele.className += ' ' + cls;
        }
    }

    function removeClass(ele, cls) {
        if (hasClass(ele, cls)) {
            var reg = new RegExp('(\\\\s|^)' + cls + '(\\\\s|$)'),
                newClass = ele.className.replace(reg, ' ');
            ele.className = newClass.replace(/^\\s+|\\s+$/g, '');
        }
    }

    function getMainClassElementAbove(element) {
        var parentElement = element.parentNode;
        while (!hasClass(parentElement, 'main-class') && parentElement.nodeName !== 'BODY') {
            parentElement = parentElement.parentNode;
        }

        return parentElement;
    }

    function getDivBelow(element) {
        return element.querySelector('div');
    }

    function getDivBelowMainClass(element) {
        var mainClassElement = getMainClassElementAbove(element);

        return getDivBelow(mainClassElement);
    }

    function addClassToFirstDivOfMainClass(evt) {
        evt = evt || window.event;
        var clickedElement = evt.target || evt.srcElement,
            target;

        target = getDivBelowMainClass(clickedElement);
        addClass(target, 'the-new-class-added');
    }

    var containers = document.querySelectorAll('.main-class'),
        i;
    for (i = 0; i < containers.length; i += 1) {
        containers[i].onclick = addClassToFirstDivOfMainClass;
    }
}());&#8203;