Is there any way to get the content of an HTML element -where the function is called- without having to identify it by ID or class name ?
example instead of using :
<button class="colm" type="button" onclick="show('1')">1</button>
we use something like :
<button class="colm" type="button" onclick="show(getThisElementContent())">1</button>
My point is to ask if it's possible to make this function per say we call it getThisElementContent() that is able to extraxt the innerHTML from the Element where it is called in our case the element innerHTML is 1.
Sure, define a function named logElem :
const logElem = (elem) => console.log({elem});
then in HTML :
<div onclick="logElem(this)">CLICK ME</div>
Cheers
There are a couple ways, the simplest include:
Passing this to the inline event handler:
function showContent(element) {
console.log(element.textContent);
}
<button class="colm" type="button" onclick="showContent(this)">1</button>
Adding the event via JS and accessing the event target:
document.querySelector('.colm').addEventListener('click', showContent);
function showContent(event) {
console.log(event.target.textContent);
}
<button class="colm" type="button">1</button>
Yes, there is. You need to add an event listener in JavaScript so you can handle the mouse click event when it happens.
<html>
<body>
<button id="myButton">
Click Me
</button>
</body>
<script>
const button = document.getElementById("myButton")
button.addEventListener('click', e => {
console.log(e.target.innerHTML);
});
</script>
</html>
The second argument to addEventListener is a callback function that will get executed when the click event happens on the button. This function will receive a parameter, in this case I called it e which is of type Event, which you can read about here - https://developer.mozilla.org/en-US/docs/Web/API/Event
This Event object has a target attribute which is a reference to the object to which the event was originally dispatched, the button.