nick
nick

Reputation: 1246

Jquery, on click get this elment's text and store it in varible

I am trying to store the text inside a DOM element into a jQuery variable. My goal is to get the text inside of the span with class of "getText". I want to be able to click on any of the td and only get the text of the one I clicked.

here is my code:

<table>
 <tbody>
    <tr>
    <th class="option1">ignore me<span class="getText">option 1 text<span></th> 
    <th class="option2">ignore me<span class="getText">option 2 text<span></th> 
    <th class="option3">ignore me<span class="getText">option 3 text<span></th> 
    <th class="option4">ignore me<span class="getText">option 4 text<span></th> 
   </tr> 
 </tbody>

$("th").click(function(event) {
  var getElemntSelector = (this.className); 
  getElemntSelector =  '".' + getElemntSelector +' .getText"';
  getElemntSelector =  '$('+ getElemntSelector +')'; //$(".option1 .getText")
  getElemntSelector = getElemntSelector.text();
  console.log(getElemntSelector);
});

When I console log the variable I attempted store the text in I get this error:

TypeError: getElemntSelector.text is not a function

Is this because my variable getElemntSelector is still a string? here is my fiddle: https://jsfiddle.net/a7yqhtm5/

Upvotes: 0

Views: 73

Answers (2)

Ivelin Ivanov
Ivelin Ivanov

Reputation: 168

You can try this $(this).children(".getText").text() it will select the children which has 'getText' class and then get it's text

Upvotes: 1

Domain
Domain

Reputation: 11808

You can use 'hasClass' method to get text of inner element.To get your desired output please write following statement in js file.

 $("th").click(function(event) {
    if($( this ).children().hasClass( "getText" )){
         //You can use following statement to store in to js variable
         console.log($( this ).children().text());
    }

    });

You can check this example using following link:

https://jsfiddle.net/a7yqhtm5/4/

Upvotes: 0

Related Questions