Forum Moderators: open

Message Too Old, No Replies

Walk DOM relative to script tag

         

heisters

11:59 pm on Aug 20, 2007 (gmt 0)

10+ Year Member



Say I have some XHTML like this:


<p>Foo</p>
<script type="text/javascript">
// Magic
</script>

Is there any way for Magic to reference the script tag? So that I could walk up to <p>Foo</p> and do something to it without assigning anything an unneeded id attribute?

TIA!

daveVk

4:36 am on Aug 21, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I dont think the Dom includes the script.

heisters

9:06 pm on Aug 21, 2007 (gmt 0)

10+ Year Member



well is there any way to get the "current location" or somesuch? Hm, I guess I could use ye olde onload= attribute probably... funny all this Prototype and behavior-layer stuff makes me forget the basics.

Little_G

9:14 pm on Aug 21, 2007 (gmt 0)

10+ Year Member



Hi,

If you are only going to have one script tag in your document, or you know that the script your trying to find will always be the second (or third...) then you can find it by using

document.getElementsByTagName('script')[[i]index[/i]]
.
If not then I don't know any simple way of doing it, there may be ways of hacking it.

Andrew

heisters

11:02 pm on Aug 21, 2007 (gmt 0)

10+ Year Member



No, it really needs to be relative, since there might be multiple of these in a single page. And my onload idea doesn't work because only body can have onload..

Little_G

11:25 pm on Aug 21, 2007 (gmt 0)

10+ Year Member



Hi,

Ok then I put together this possible solution it may not be the best it isn't the most attractive:

[pre]<html>
<head>
<script type="text/javascript">
function findPreviousSibling(){
var id = "temp" + Math.floor(Math.random()*100000);
document.write('<span style="display:none;" id="' + id + '"></span>');
var r = document.getElementById(id).previousSibling;
var c = 0;
return r.previousSibling.previousSibling;
}
</script>
</head>
<body>
<p>test</p>
<script type="text/javascript">
alert(findPreviousSibling());
</script>
</body>
</html>[/pre]

Andrew

heisters

1:00 am on Aug 22, 2007 (gmt 0)

10+ Year Member



heh, that's wicked hackish. Thanks, I'll play around with that. Not exactly elegant, but it might just work.