Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the current element in Javascript? [duplicate]

How can I find out what the element is that a <script> sits in?
As an example, let's take this

<div>
 <script type="text/javascript">
  var time = new Date(), hrs = time.getHours(), min = time.getMinutes();
  document.write('It is '+hrs+":"+(min<10?'0':'')+min);
 </script>
</div>

Then if I want to change this to something more modern, how can I find out what element we're in?
So I want to write, for instance in jQuery

$(thisdiv).html('It is '+hrs+":"+(min<10?'0':'')+min);

but how do I get thisdiv?
Yes, I know, I can put an ID on it, but I have the feeling that wouldn't be necessary. The browser knows where we are, otherwise it couldn't even do the document.write!

So, suggestions? I searched, but couldn't find it. Is it so simple that I'm overlooking the obvious?

like image 424
Mr Lister Avatar asked Feb 09 '12 11:02

Mr Lister


People also ask

What are the duplicate elements?

Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.

How do you check if a number is repeated in an array JavaScript?

To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.


2 Answers

Script are executed in the order of appearance in the document. The contents of a script tag are evaluated on encounter, so, the last <script> element is always the current one.

Code:

<div>
  <script>
    var scriptTag = document.getElementsByTagName('script');
    scriptTag = scriptTag[scriptTag.length - 1];

    var parent = scriptTag.parentNode;
  </script>
</div>
like image 105
Rob W Avatar answered Oct 14 '22 06:10

Rob W


Firefox:

document.currentScript.parentElement

Chrome:

document.scripts.length
like image 37
Phil H Avatar answered Oct 14 '22 07:10

Phil H