Reputation: 51
I have a following divs that are grouped into three layers. I need to get the text of the clicked element like for example they clicked "123" I will be able to record it.
<div class="Div1st">
<div class="Di2ndv">
<div class="Div3rd">123</div>
<div class="Div3rd">abc</div>
</div>
<div class="Div2nd">
<div class="Div3rd">def</div>
<div class="Div3rd">456</div>
</div>
</div>
"Class Names" are only meant to clearly show the hierarchy(layers) of the divs
I tried doing the code below but it only works on until 2nd Div. If I went deeper like in 3rd div it doesn't show anything.
$(".Div1st > div").click(function (e) {
alert($(this).find('div').text());
});
Upvotes: 1
Views: 52
Reputation: 11213
Can you do this?
<div class="1stDiv ">
<div class="2ndDiv ">
<div class="3rdDiv ">123</div>
<div class="3rdDiv ">abc</div>
</div>
<div class="2ndDiv ">
<div class="3rdDiv ">def</div>
<div class="3rdDiv ">456</div>
</div>
</div>
then
$("div").click(function (e) {
alert($(this).text());
});
Upvotes: 0
Reputation: 2283
When you use:
$(".1stDiv > div")
jQuery only gets the children elements of the .1stDiv., which would be the 2ndDiv. To get all divs, you would use:
$(".1stDiv div")
I would of course not recommend, using $(".1stDiv div"). Instead, you should give the div elements that you want to click a class, and use the following:
$(".clickableDiv", ".1stDiv")
Update: I would recommend this: $(".clickableDiv", "#1stDiv"). This will give you better performance, because IDs in jQuery give much better performance than classes (they natively use document.GetElementById). Given the '#1stDiv' context element will only have jQuery search in that div. This will give good performance.
Upvotes: 2
Reputation: 33870
You can use target
:
$(".1stDiv > div").click(function (e) {
alert(e.target.innerHTML);
});
Upvotes: 0