0

I mean, can I add it later on, like after I closed that div?

If I can't add it in HTML, can I add that in CSS or JS? The thing is that I created website with Wordpress and Elementor.

And I can't edit page as HTML (edit source of html code), but I can add HTML code or CSS code or JS code.

So I want myFunction() to get runned when someone click on div which id is "e-title-2451".

Nikola Pavicevic
  • 21,952
  • 9
  • 25
  • 46
  • Inline event handlers like `onclick` are [not recommended](/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](/a/43459991/4642212) way of registering events. Always [use `addEventListener`](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. – Sebastian Simon Aug 28 '21 at 17:57

2 Answers2

2

<div id="e-title-2451">click on e-title-2451</div>
<script>
const myDiv = document.querySelector("#e-title-2451")
myDiv.addEventListener('click', myFunction)
function myFunction() {
  alert('something happened')
}
</script>

You can try something like:

const myDiv = document.querySelector("#e-title-2451")
myDiv.addEventListener('click', myFunction)
Nikola Pavicevic
  • 21,952
  • 9
  • 25
  • 46
  • Hey, I tried your code and nothing happens. I must be doing something wrong. Let me explain what I did: 1. I created myFunction(). 2. I opened inspect element and edited HTML code, added onclick="myFunction()" and everything worked fine. But that isn't permanent change, it's only temporary. When I refresh page, everything I added disappears. 3. Then I made another HTML block (using Elementor) and I put your code in between . And nothing happens. If anyone knows what is going on, I would appreciate his help. – Denis Talovic Aug 29 '21 at 02:37
  • I updated answer, so you can take a look. Double check element id. Ako ne ide slobodno me kontaktiraj pa da probamo sa čekićem :) Uživaj :) – Nikola Pavicevic Aug 29 '21 at 06:19
  • Thanks, this worked!! Hvala brate puno! :))) – Denis Talovic Aug 29 '21 at 11:28
  • Nema zašta, uživaj / dobro je nije trebao čekić :)) – Nikola Pavicevic Aug 29 '21 at 11:29
0

you can use event listeners :

document.querySelector("#e-title-2451").addEventlistener('click',()=>{
 //the function code you want to perform 
});

for class you can use (".e-titlr-2451")

TwistedOwl
  • 1,195
  • 1
  • 17
  • 30