0

Example html code (Looks weird but my intention is to show that the outer components can be anything)

<div>
    <div/a/p/.. myAttribute="123">
        <p>
            <a>
                <script type="text/javascript">
                    jQuery.ajax({url: "local.host?attribute= "});
                </script>
            </a>
        </p>
    </div/a/p/..>
</div>

What I want is that, from the inner script, before the ajax call is fired, I want to travel to outer parent components, till I can reach the component that has myAttribute. Then I will take the value of myAttribute and fill it into my url as "local.host?attribute= 123"

I found the closest of JQuery, but it requires to know the component type in advanced.

Any help is appreciated. Thank you very much.

Xitrum
  • 7,765
  • 26
  • 90
  • 126
  • Do you know how to get hold of the parent of the ` – James Thorpe Aug 15 '16 at 15:28
  • `jQuery.ajax({beforeSend: function() {};})` – Michelangelo Aug 15 '16 at 15:28

1 Answers1

1

I think '*[myAttribute]' will do it fine.

$(el).parents('*[myAttribute]');

To target the current script. you can use

document.currentScript;

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div>
    <div/a/p/.. myAttribute="123">
        <p>
            <a>
                <script type="text/javascript">
                     var self = document.currentScript,
                         e = $(self).closest('*[myAttribute]'),
                         attrVal = (e.attr('myAttribute') );
                         console.log( attrVal );
                    // commented 
                    // jQuery.ajax({url: "local.host?attribute="+attrVal });
                </script>
            </a>
        </p>
    </div/a/p/..>
</div>
Adam Azad
  • 11,171
  • 5
  • 29
  • 70