What is the current element in Javascript? [duplicate]

这一生的挚爱 提交于 2019-11-27 21:20:27

问题


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?


回答1:


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>



回答2:


Firefox:

document.currentScript.parentElement

Chrome:

document.scripts.length



回答3:


$('script#some_id').parent().html('blah blah');



回答4:


Try this

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


来源:https://stackoverflow.com/questions/9209823/what-is-the-current-element-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!