This is a bit goofy, as its counter-intuitive to liberating markup of Javascript, however I'm going to ask anyways.
Given this snippet:
<p>Hello</p>
<script type="text/javascript">
$(document).ready(function(){
$('relative-selector').next('p').hide();
});
</script>
<p>World</p>
This snippet would target the <script> tag itself with this "relative selector", and .next('p').hide() would result in <p>World</p> being hidden.
Does there exist a "relative selector", or means of targeting the script tag a given snippet resides within?
The answer I'm looking for (given such one exists) would not require the use of an id attribute, or any such identifying attributes; it would work with an arbitrary number of <script> tags in a given document, regardless of position in the DOM tree.
I've seen some strange implementations that don't use $(document).ready(), instead relying on the fact that the remaining markup has not loaded, using $('script:last') or some such concoction. This isn't what I'm after though; I'd like to .bind() some handlers to elements relative to the binding script snippet (typically after, which is why the unloaded markup trick won't work)
$(this) simply targets the document object due to the ready handler. $(this) outside of load-deferred handlers targets window.
I've already nearly accepted that this probably isn't possible, however I'm sure if any solution exists, its floating about in the minds of fellow SO users.
You can probably insert a temporary element using
document.write("<div id='temp' style='display: none'></div>")
and then using that to find the next element using jQuery. Afterwards you can remove the element.
$("#temp").next("p").doSomething();
$("#temp").remove();
Another option would be to build on the technique you suggested of the partialy loaded document to retrieve a reference to the tag, but to use it only on load:
(function() {
var thisScript = $('script:last');
$(function() {
thisSctipt.next("p").doSomething();
});
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With