简体   繁体   English

使用 document.getElementById 注入元素在 Javascript 中不起作用

[英]injecting element using the document.getElementById is not working in Javascript

I have written a small javascript code and now need to inject the result into my HTML.我已经编写了一个小的 javascript 代码,现在需要将结果注入到我的 HTML 中。 I have inspected the windows element and even copied the specific selector for that element but it still doesn't inject the answer into it.我检查了 windows 元素,甚至复制了该元素的特定选择器,但它仍然没有将答案注入其中。 I am trying to insert it into the span tag in the HTML code.我试图将它插入到 HTML 代码中的 span 标签中。

 const str = new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' }); console.log(str); document.getElementById('#us').textContent = str
 <div class="header-button-item js-item-menu"> <i class="zmdi zmdi-settings"></i> <div class="setting-dropdown js-dropdown"> <div class="account-dropdown__body"> <div class="account-dropdown__item"> <a href="#"><i class="zmdi zmdi-email"></i>America Time&nbsp;&nbsp; - <span id="us"></span></a> </div> </div> </div> </div>

You could try this:你可以试试这个:

 const str = new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' }); console.log(str); document.getElementById('us').innerHTML = str

Thanks to you all, I was able to solve it after going through all the comments.感谢大家,在浏览了所有评论后,我能够解决它。

my mistake was using the # together with the getElementById.我的错误是将 # 与 getElementById 一起使用。 So, I had to remove the # which then made it work well.所以,我不得不删除 # 然后让它运行良好。

But if you need to use the # then you can go with something like getSelector.但是如果你需要使用#,那么你可以使用 getSelector 之类的 go。

document.getElementById('us').textContent = us_time 

or

document.getSelector('#us').textContent = us_time 

You're getting confused with querySelector .您对querySelector感到困惑。

 const str = new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' }); console.log(str); document.querySelector('#us').textContent = str
 <div class="header-button-item js-item-menu"> <i class="zmdi zmdi-settings"></i> <div class="setting-dropdown js-dropdown"> <div class="account-dropdown__body"> <div class="account-dropdown__item"> <a href="#"><i class="zmdi zmdi-email"></i>America Time&nbsp;&nbsp; - <span id="us"></span></a> </div> </div> </div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM