Question

I have the following code:

<div>    
  <span id='1' onclick="GetValue();">Some value</span>
  <span id='2'>Some Span
     <span id='3'>Want this text</span>
  </span>
</div>

 <div>    
  <span id='1' onclick="GetValue();">Some value</span>
  <span id='2'>Some Span
     <span id='3'>Want this text</span>
  </span>
</div>

I need to get the text from span id=3 and this is what I have:

  function GetValue() {
     var get_text= $(this).next().find("#3").text();
     alert(get_text);
  }
Was it helpful?

Solution

Firstly you can directly get the text using id selector like this

$('#myId').text();

Second id attribute's value should not be start with digit. It must be start with character and then it may followed by digit.

The issue with your code is that your $(this) is basically a window object not the span which trigger the click.

So you need to something like this

function GetValue(element) {
     var get_text= $(element).next().find("#three").text();
     alert(get_text);
}

with HTML

<span id='one' onclick="GetValue(this);">Some value</span>
  <span id='two'>Some Span
     <span id='three'>Want this text</span>
  </span>

Js Fiddle Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top