What is the difference between $ ('# id') and document.querySelector ('# id')?

2

Is not it supposed to get the same result using one method or the other? I added a listener oncick and only using the second method could actually declare the event listener . Why?

var record = document.querySelector('#record');

record.onclick = function(){

alert("Entrou!");

}

var record2 = $('#record2');

record2.onclick = function(){

alert("Não vai entrar!");

}
    <!--UPDATE-->
    var record3 = $('#record3');
record3.on('click', function(){ alert('Vai entrar sim!'); });
<script
  src="https://code.jquery.com/jquery-3.2.1.slim.min.js"integrity="sha256-k2WSCIexGzOj3Euiig+TlR8gA0EmPjuc79OEeY5L45g="
  crossorigin="anonymous"></script>
  
  <button type="button" id="record">Record</button>
    <button type="button" id="record2">Record 2</button>
    
    <!--UPDATE-->
    
     <button type="button" id="record3">Record 3</button>
    
asked by anonymous 28.11.2017 / 12:37

2 answers

6

The first one you use alias to use jQuery, while in the second it uses the DOM with JavaScript only.

var record = document.querySelector('#record');
record.onclick = function(){
alert("Entrou!");
}

var record3 = $('#record3');
record3.on('click', function(){ 
alert('Vai entrar sim!');
});
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"integrity="sha256-k2WSCIexGzOj3Euiig+TlR8gA0EmPjuc79OEeY5L45g=" crossorigin="anonymous"></script>
  
<button type="button" id="record">Record</button>
<button type="button" id="record3">Record 3</button>

What you missed was mixing jQuery with JavaScript. While you can mix, it's important to understand that jQuery and native JavaScript refer to DOM elements differently. Here you should be aware that record , record2 and record3 are not the same thing. One is a DOM element and the other is a jQuery object that contains a value.

var record2 = $('#record2');
record2.onclick = function(){
  alert("Não vai entrar!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttontype="button" id="record2">Record 2</button>
    
28.11.2017 / 12:57
0

Does not work for the simple reason of the return of each function:

document.querySelector('#record'); // retorna um [object HTMLButtonElement]
$('#record2');  // retorna um [object Object]

To work properly, you need to treat it correctly:

var record = document.querySelector('#record');
record.onclick = function(){
  alert("Entrou!");
}

$('#record2').on('click', function(){ 
  alert('Vai entrar sim!'); 
});
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"integrity="sha256-k2WSCIexGzOj3Euiig+TlR8gA0EmPjuc79OEeY5L45g=" crossorigin="anonymous"></script>
 
<button type="button" id="record">Record</button>
<button type="button" id="record2">Record 2</button>
    
28.11.2017 / 13:00