OSMQuote
OSMQuote

Reputation: 297

Get clicked letter from p tag

I am trying to get the letter clicked in p tag using javascript. But instead of getting a single word, I am getting the whole tag.

function myFunction() {
        var s = document.getSelection()
        var node = s.anchorNode
        console.log(node)
        var item = node.nodeValue.trim()
        alert(item)
    }
p{
font-size:3rem;
font-style: normal;
}
<p onclick="myFunction()">😃🧘♂️🌍🍞🚗🎉♥️🍆</p>

can anyone help me?

Upvotes: 1

Views: 964

Answers (2)

Kinglish
Kinglish

Reputation: 23654

You can map the list of letters into individual elements, which would allow the event listener target to return the individual letter.

window.addEventListener('load', () => {
  let letters = document.querySelector('.letters');
  letters.innerHTML = letters.innerText.split('').map(l => `<span>${l}</span>`).join('');
  document.querySelector('.letters').addEventListener('click', e => {
    console.log(e.target.innerText);
  })
})
p {
  font-size: 3rem;
}
<p class='letters'>ABCDEFGHIJKLMNOPQRSTUVWXYZ</p>

Upvotes: 3

dale landry
dale landry

Reputation: 8600

You have a string within an element, the element is clickable and can have an event on it. However, to determine the exact character you are clicking on you will need to wrap the character in an element that can be identified as its own selector.

One way to do this would be to get the textContent of the element (the characters), split the string creating an array of each character. Then iterate over that array and create a span tag, add a class to it for click events, and place each characters value into each span tag. Then append each tag back into the element.

Then you can create an eventListener that listens for clicks on the class that was added.

function getChar(e) {
  console.log(e.target.textContent)
}

function createClickables() {
  const str = document.querySelector('.info')
  const parts = str.textContent.split('')
  str.textContent = ''
  parts.forEach(char => {
    let span = document.createElement('SPAN')
    span.textContent = char
    span.classList.add('char')
    str.append(span)
  })
}

createClickables()

const chars = document.querySelectorAll('.char')
chars.forEach(item => {
  item.addEventListener('click', getChar)
})
p {
  font-size: 3rem;
}

.char {
  cursor: pointer;
}
<p class="info">ABCDEFGHIJKLMNOPQRSTUVWXYZ</p>

Upvotes: 1

Related Questions