-1

Both codes below do the same thing, first using Vanilla JS and second using JQuery. JQuery code do not have to insert anything inside html tags, while JS have to insert the caller "onclick="myFunction()"".

How could I modify the JS code so that I have no need to insert anything inside html tags, exactly like JQuery code does?

Vanilla JS Code:

<!DOCTYPE html>
<html>
<body>
<p onclick="myFunction()">Click on this paragraph</button>
<script>
function myFunction() {
  alert("The paragraph was clicked.");
}
</script>
</body>
</html>

JQuery Code:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("p").click(function(){
        alert("The paragraph was clicked.");
    });
});
</script>
</head>
<body>
<p>Click on this paragraph.</p>
</body>
</html>
1
  • 1
    JS is perfectly capable of attaching event listeners. Array.from(document.querySelectorAll("p")).forEach(function(p) {p.addEventListener('click',myFunction);}); function myFunction(e) {alert('You clicked on '+this);} Commented May 3, 2018 at 11:19

6 Answers 6

5

You can use addEventListener on your p tag.

getElementsByTagName('p')[0] will return array of p tags, in your case you need add listener to single paragraph (its index 0, thats why we have [0])

<!DOCTYPE html>
<html>
<body>
<p>Click on this paragraph</p>
<script>
  document.getElementsByTagName("p")[0].addEventListener("click", function() {
    alert('The paragraph was clicked.')
  });
</script>
</body>
</html>

Sign up to request clarification or add additional context in comments.

2 Comments

Please, what should I change in order to your code works inside an separate .js file? I tried to do that but a got the following error: "Uncaught TypeError: Cannot read property 'addEventListener' of undefined". I thought if the code works internally it should works externally as well, without any changes.
Found the awswer: we have to add the following code: window.onload = function () { PASTE HERE THE ORIGINAL INTERNAL JS CODE}. Found the awswer here:stackoverflow.com/questions/42341761/…
4

You just need to select the element and assign it to a variable. Then you can use an onclick function or addEventListener.

var pElem = document.querySelector('p');

pElem.onclick = function() {
alert("The paragraph was clicked.");
}
<p>Click on this paragraph</p>

Or if you want to apply it to all paragraph tags you can loop through the elements and assign a click function:

var pElems = document.querySelectorAll('p');
Array.prototype.forEach.call(pElems, function(el, i){

  el.onclick = function() {
  alert("The paragraph was clicked.");
  }

});
<p>Click on this paragraph</p>

<p>Click on this paragraph</p>

<p>Click on this paragraph</p>

Comments

2

I think this might be what you are looking for?

 document.getElementById("buttonID").onclick = function() { 
        alert('Button Clicked'); }

Basically this adds the onclick event to the button with buttonID id.

Comments

2

addEventListener will help you out:

var p = document.getElementsByTagName('p')[0];
p.addEventListener('click', function myFunction() {
  alert("The paragraph was clicked.");
});
<p>Click on this paragraph</p>

Comments

2

The thing is that jQuery internally adds the event listener to the selector with the addEventListener. Thats basically what the onclick attribute does in HTML.

const run = () => console.log('Button 3 clicked');

// js
document.getElementById('b1').addEventListener('click', () => {
  console.log('Button 1 clicked');
})

//jquery
$('#b2').on('click', () => {
  console.log('Button 2 clicked');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="b1">Click 1</button>

<button id="b2">Click 2</button>

<button onclick="run()">Click 3</button>

Comments

2

First, target your specific HTML element with for instance document.querySelector(). So you can access one specific element by its class for example, just like jQuery does.

Second, add an event listener with .addEventListener() and specify it with the event click.

document.querySelector('.mybutton').addEventListener('click', function(){
  alert('Ouch, that hurts!');
});
<button class="mybutton">Click me</button>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.