Search code examples
javascriptjqueryfindparentclassname

Get parent form class when you click on an element jQuery


Let's start with the HTML:

<form class="send_units">
    <div class="buttons">
        <div id="button_attack" class="button">
            <div class="caption at">Attack!</div>
        </div>
        <div id="button_support" class="button">
            <div class="caption sp">Support!</div>
        </div>
    </div>
</form>

This is an example of the code on a website. I've made a script for that website. To run that script, a player can use Tampermonkey. It just adds some code to the webpage. Note: We cannot change the HTML!

So, I've to get the classname of the form (send_units in this example), when you click on the Attack! button.

To figure out on which element the user clicks, we use Javascript:

window.onclick = function(e){
    var clickedClass = e.target.className;
    var clickedID = e.target.id;

    if(clickedClass == 'caption at'){
        // Check if parent form has class send_units
    }
}

So, when the user clicks on the button with class = 'caption at', we have to check if the form class is send_units.

I've tried this to get the class:

jQuery(e).find('form').parent().prop('class')

but it returns "undefined". (Logic says to me: Get the parent of the clicked element, with element "form" and get the className of that element).

Can anyone explains to me what I'm doing wrong here?

Thanks!


Solution

  • Use .parents( selector ) to traverse multiple levels up the DOM to the element you need and .hasClass( class ) to test for presence of a class.

    window.onclick = function(e){
        var clickedClass = e.target.className;
        var clickedID = e.target.id;
    
        if(clickedClass == 'caption at'){
        	var is_send_units = $( e.target ).parents( 'form' ).hasClass( 'send_units' );
            console.log( is_send_units );
            if( is_send_units ){
              // do stuff
            }
        }
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form class="send_units">
        <div class="buttons">
            <div id="button_attack" class="button">
                <div class="caption at">Attack!</div>
            </div>
            <div id="button_support" class="button">
                <div class="caption sp">Support!</div>
            </div>
        </div>
    </form>