Say I have a div container with multiple divs with some width and height. I want to get the text within a div clicked.
<div id="containId">
<div>Sometext1
<div class="description">This is a desc</div>
</div>
<div>Sometext2
<div class="description">This is a desc</div>
</div>
<div>Sometext3
<div class="description">This is a desc</div>
</div>
<div>Sometext4
<div class="description">This is a desc</div>
</div>
<div>Sometext5
<div class="description">This is a desc</div>
</div>
</div>
How do I make it so that when the user clicks on a div within containId, I can get the text into a variable (just the Sometext# part and not the description divs within those divs)?
This should do it:
It works as follows:
.contents()returns a jQuery object containing all child nodes, not only elements nodes..map()is used to filter out non-text nodes and retrieve the text value of text nodes.DEMO
This will retrieve the value of all text nodes, not only the first one. If you only want to get the value of the first text node, use @karim’s answer (simpler).