Akram Berkawy
Akram Berkawy

Reputation: 5060

JQuery selector of script tag calling from

i have the following html output of a tool thats i'm developing:

<button>a</button>
<script>$('what to wrtie here to select the previous button element?').click(function(){alert ('a clicked !');});</script>
<button>b</button>
<script>$('same here').click(function(){alert ('b clicked !');});</script>

i need the selector in each script tag to select the previous element. using id selector cant be applied since the tool don't generate ids for elements.

thanks.

ANSWER:

$('script').last().prev().click(...

as Niklas said the current executed script is the last one in the list

Upvotes: 1

Views: 2431

Answers (3)

user1726343
user1726343

Reputation:

There is no way of doing this (referring to the script tag that contains the script) that I know of. The best approach here would be to generate an ID for each element and aggregate your script into a single script tag.


That up there is the correct solution. The secret, naughty solution is this (spoiler):

<button>a</button>
<script> //script#0001 $('script:contains("#0001")').prev().click(function(){ alert('foo'); });
</script>

<button>b</button>
<script> //script#0002 $('script:contains("#0002")').prev().click(function(){ alert('bar');
});
</script>

DON'T USE IT

Upvotes: 1

Niklas
Niklas

Reputation: 13145

This is not possible without an id or some other kind of reference to either the button object or the script tag itself.

It's not possible to do because the script is not executed from where its element is located in the DOM. Instead it's executed with reference to the whole window.

Actually, there's a pretty good answer here: How may I reference the script tag that loaded the currently-executing script?

In short, the currently running script is the last element in the list.

Upvotes: 3

Nadeem Khedr
Nadeem Khedr

Reputation: 5313

well , i really don't recommend what you are doing first lets talk about your approach, this kind of code should be wrapped in a ready event and when the DOM is ready all the registered code associated with that event will run , so no way to understand what script tag the code were in


what should happen is moving all the script tags to its own file and using selectors to select what elements you want or selecting them dynamicly using prev,next, parents, etc

Edit

i am wrong about not being able to get the script tag @Niklas answer is the right one, but i am still thinking very wrong to do so

Upvotes: 1

Related Questions