N. Ayancan N. Ayancan - 7 months ago 16
HTML Question

How to get html text from a relative element using JQuery?

So I'm trying to get the specific text inside an HTML tag which is a relative from it. The thing is that I have multiple Parents, which means I have multiple calls and diferent texts wanted.

As an example:

<parent>
<child>
<grandchild class="wanted">Text</grandchild>
<grandchild></grandchild>
</child>
<child>
<grandchild></grandchild>
<grandchild></grandchild>
</child>
<child>
<grandchild class="calling"></grandchild>
<grandchild></grandchild>
</child>
</parent>


And my script

$(document).ready(function(){
$(".calling").click(function(){
var message = $(this).parent().siblings(".wanted").html();
});
});


The thing is that I cannot get the Text wanted, and I don't know if I have to parse or not, even when I've already tried so.
I hope you can help me.

Answer

The thing is that I cannot get the Text wanted, and I don't know if I have to parse or not, even when I've already tried so. I hope you can help me.

This is because you are doing var message = $(this).parent().siblings(".wanted").html();

$(this) -> calling class(grandchild)

$(this).parent() -> <child></child>(3rd one)

$(this).parent().siblings() will give other <child> elements(1st and 2nd one)

Therefore you should be doing $(this).parent().siblings().find('.wanted') so that it can find the grandchild inside the sibling(<child>).