Olawale Akinseye
Olawale Akinseye

Reputation: 177

How to get the html content of a clicked element using jQuery

I am trying to get the inner html content of a particularly clicked div, I have a number of div elements.

Look at the code I use below.

$(function() {

    $( "#try" ).click(function() {
        var clickedValue = $(this).find('div').text();
        alert(clickedValue);
    });

});
<div id="try">
    <div class="cchoice" style="background-color: blue;">B</div> 
    <div class="cchoice" style="background-color: red;">R</div> 
    <div class="cchoice" style="background-color: yellow;">Y</div> 
    <div class="cchoice" style="background-color: black;">B</div> 
    <div class="cchoice" style="background-color: gray;">G</div> 
    <div class="cchoice" style="background-color: white;">W</div> 
</div>

I want to do it in a way such that B appears when the div with background color of blue is clicked on but then it seems something is wrong with the way I am doing it. For some reasons, I cannot give id attribute to those set of div and they must have the same class.

The problem with the code above is that when I click on any of the 6 div elements, the clickedvalue will be BRYBGW.

Upvotes: 2

Views: 1997

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

$(this).find('div') will return all the div elements within the #try element, instead you want to target only the clicked div

You can use event.target

$(function() {
  $("#try").click(function(e) {
    var clickedValue = $(e.target).text();
    alert(clickedValue);
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="try">
  <div class="cchoice" style="background-color: blue;">B</div>
  <div class="cchoice" style="background-color: red;">R</div>
  <div class="cchoice" style="background-color: yellow;">Y</div>
  <div class="cchoice" style="background-color: black;">B</div>
  <div class="cchoice" style="background-color: gray;">G</div>
  <div class="cchoice" style="background-color: white;">W</div>
</div>


But I would recommend targeting the actual child element using the click handler.... either by directly binding the handler to them or by using event delegation

$(function() {
  //or $("#try > div").click(function(e) {
  $("#try").on('click', 'div', function(e) {
    var clickedValue = $(this).html();
    alert(clickedValue);
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="try">
  <div class="cchoice" style="background-color: blue;">B</div>
  <div class="cchoice" style="background-color: red;">R</div>
  <div class="cchoice" style="background-color: yellow;">Y</div>
  <div class="cchoice" style="background-color: black;">B</div>
  <div class="cchoice" style="background-color: gray;">G</div>
  <div class="cchoice" style="background-color: white;">W</div>
</div>

Upvotes: 8

Related Questions