scrummy
scrummy

Reputation: 795

JavaScript Get Selected Item's TextContent

I want to make a program that write out the textContent of the item that has clicked. For some reason this program only get the last element's content. Any idea what should I change inside the for loop?

var emailname = document.querySelectorAll(".name");

var gSenderName = document.getElementById('sname');

$('.name').click(function() {

  for (var i = 0; i < emailname.length; i++) {
    const sendername = emailname[i].textContent;
    gSenderName.textContent = sendername;

  }

});
.name:hover {
  text-decoration: underline;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name">first</div><br>
<div class="name">second</div><br>
<div class="name">third</div>
<br>

<div>Selected:
  <div id="sname"></div>
</div>

Upvotes: 0

Views: 230

Answers (2)

Mamun
Mamun

Reputation: 68933

You do not need the loop here at all. You can simply get the currently clicked element's text by using this object. I will also suggest you not mix up vanilla JS and jQuery unnecessarily:

var gSenderName = $('#sname');

$('.name').click(function(){
  gSenderName.text($(this).text());
});
.name:hover {
  text-decoration: underline;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name">first</div><br>
<div class="name">second</div><br>
<div class="name">third</div>
<br>

<div>Selected: 
  <div id="sname"></div>
</div>

Upvotes: 2

Ori Drori
Ori Drori

Reputation: 191976

The loop runs and sets the text content of each item one after the other. Because each override the other, you always get the last one.

Just set the text content of the element that was clicked:

var gSenderName = document.getElementById('sname');

$('.name').click(e => {
  gSenderName.textContent = e.target.textContent;
});
.name:hover {
  text-decoration: underline;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name">first</div><br>
<div class="name">second</div><br>
<div class="name">third</div>
<br>

<div>Selected:
  <div id="sname"></div>
</div>

Upvotes: 1

Related Questions