Search code examples
javascriptinnerhtmlcpu-word

javascript, on click change the html of an element different than the one that was clicked on


I am trying to change the innerhtml of a p tag by clicking on a word, but I do not want to change the innerhtml of the word that I clicked on. I want to change the word that is displayed next to the word that I clicked on.

my html looks like this. each id of the word clicked on is followed by a black p tag with an id that is one more than the one that was clicked on

<p id="word0" data-index=0 class="russian"> люблю</p>
<p id="word1" data-index=1 class="english"></p>

the black p tag for the english word should be filled in by the english word when i click on the russian word.

here is my javascript. for the time being the words one two three ect, will be placed next to the russian word when it is clicked. is there a way that i can target the innerHTML of the tag next to the word that is clicked on?

<script>

    let allWordsList = {'word0':'one','word1':'one','word2':'two','word3':'three'}


    function changeText(e){
        var number = e.target.id;

       // Set the text to the data-index value of the HTML element:
       e.target.innerHTML = allWordsList[number];

    }

</script>

Solution

  • You are changing the innerHTML of the clicked element. e is the event for the para on which you clicked and e.target is the HTML element on which you clicked. So if you change the innerHTML of e.target then it would change its own not its next sibling.

    e.target.innerHTML = allWordsList[number];
    

    one way to solve this is:

    let allWordsList = {
      'word0': 'one',
      'word1': 'one',
      'word2': 'two',
      'word3': 'three'
    }
    
    
    function changeText(e) {
      var number = e.target.id;
      var convertedNumber = allWordsList[ number ];
      //Set the text to the data-index value of the HTML element:
      const nextSibling = e.target.nextElementSibling;
      nextSibling.innerHTML = convertedNumber;
    }
    
    const paragraphs = document.querySelectorAll(".para");
    paragraphs.forEach( e => {
      e.addEventListener("click", changeText);
    })
    <p id="word0" data-index=0 class="russian para"> люблю</p>
    <p id="word1" data-index=1 class="english"></p>
    
    <p id="word2" data-index=0 class="russian para"> люблю</p>
    <p id="word3" data-index=1 class="english"></p>