0

Am trying to build a function that takes the inner text from an HTML button, and maps it onto a variable. The below function is working, is there a way to map the innterText from the button it is activated by onto the dir var?

When I console.log ~ this ~ I get the path to the website from my computer.

function otterSummon() {
    removeImages();
    var imgCount = 79;
    var dir = 'otters/';
    var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
    var otterImage = document.createElement('img');
    otterImage.src = dir + images[randomCount];
    otterImage.setAttribute("id", "memeImage");
    var container = document.getElementById("containerMain");
    container.appendChild(otterImage);
    console.log(this)
    console.log(otterImage);
}
Airrivas
  • 5
  • 1
  • Who calls the function otterSummon ? – Aks Jacoves Jun 13 '20 at 23:56
  • Second. If this is on a webpage, can you include the entire page? – EricMPastore Jun 13 '20 at 23:59
  • If `otterSummon()` is an event handler, `this` will point to the element that triggered the event. Try `console.dir(this)` for more readable output. https://stackoverflow.com/questions/17665489/using-this-inside-an-event-handler – Don't Panic Jun 14 '20 at 01:03
  • @AksJacoves an html button. There are two other functions which are identical but call images from different folders. If I could get the buttons to throw their innertext, I could rename the folders to match the inner text and just have one function for all three buttons, that's the dream. – Airrivas Jun 15 '20 at 01:05
  • @EricMPastore the entire page itself is 150+ lines of code, so it's a lot to get through. It's on Github though @ https://github.com/AirRivas/Alexis – Airrivas Jun 15 '20 at 01:07
  • @Don'tPanic It gives me a readout for the entire site and strangely console.log(this) is just ignored on the console. Nothing prints onto console when the function is run, not even an undefined. I'm clearly very new at this, but I am stumped. – Airrivas Jun 15 '20 at 01:13
  • See if the answer to your question resolves – Aks Jacoves Jun 15 '20 at 01:15

1 Answers1

1

Try to put this as a parameter in the function call on the button, and then it's easy to access its properties.

function otterSummon(button) {
  console.log(button.textContent)
}
<button onclick="otterSummon(this)">CLICK-ME</button>