最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - getElementById returns null? (with Vue) - Stack Overflow

programmeradmin3浏览0评论

So I tried to find the answer, but no success.

window.onload = function() {
   console.log(document.getElementById('#sell'));
   if(document.getElementById('#sell')){
      alert('jo');
      //Init for Vue
   }
}

It works with jQuery but not with vanilla JS why?

console.log(document.getElementById('#sell')); 

Result returns NULL.

jQuery example:

if ( $( "#sell" ).length ) {
   const app = new Vue({
          el: '#sell',
          ponents: { sellPicture }
   });
}

In my sell.blade.php it looks like that

... 
<div id="sell">
    <sell-picture></sell-picture>
</div>
....

My script is added before /body

Just a side question. I need jQuery for Bootstrap, is it bad to use it also in Vue if I don't change the DOM with it?

So I tried to find the answer, but no success.

window.onload = function() {
   console.log(document.getElementById('#sell'));
   if(document.getElementById('#sell')){
      alert('jo');
      //Init for Vue
   }
}

It works with jQuery but not with vanilla JS why?

console.log(document.getElementById('#sell')); 

Result returns NULL.

jQuery example:

if ( $( "#sell" ).length ) {
   const app = new Vue({
          el: '#sell',
          ponents: { sellPicture }
   });
}

In my sell.blade.php it looks like that

... 
<div id="sell">
    <sell-picture></sell-picture>
</div>
....

My script is added before /body

Just a side question. I need jQuery for Bootstrap, is it bad to use it also in Vue if I don't change the DOM with it?

Share Improve this question edited Jan 4, 2018 at 11:06 Dexygen 12.6k13 gold badges86 silver badges151 bronze badges asked Jan 4, 2018 at 10:53 Philipp MochinePhilipp Mochine 4,71512 gold badges43 silver badges81 bronze badges 1
  • 3 Try document.getElementById('sell') without hashtag – Stéphane Ammar Commented Jan 4, 2018 at 10:54
Add a ment  | 

3 Answers 3

Reset to default 4

Remove # from the id param like below

window.onload = function() {
   console.log(document.getElementById('sell'));
   if(document.getElementById('sell')){
      alert('jo');
      //Init for Vue
   }
}

document.getElementById('#sell') does not require a # to identify Ids. That is the syntax you would use in a jQuery selector, but a DOM selector will literally take the string and match it against the ID attribute value. The same goes for document.getElementByClassName(), where you would not need a . to identify the class.

The Mozilla MDN documentation gives an example of this here.

This should work:

window.onload = function() {
   console.log(document.getElementById('sell'));
   if(document.getElementById('sell')){
      alert('jo');
      //Init for Vue
   }
}

Please try to use

$(document).ready(function(){ console.log($("#sell")); });
发布评论

评论列表(0)

  1. 暂无评论