1

Trying to get the child of a parent through a child accessor. Basically trying to get the .block__id through the add__block class.

HTML

<div class="col-12"> <span class="block__id">{{$block->id}}</span> {{$block->title}} <span class="add__block">+</span> </div> 

jQuery

$(".add__block").click(function(){ $(this).parent().find(function(){ var id = $(".block__id").text(); }); console.log(id); }); 

Currently I get id not defined.

1
  • @pravid it's already in the question...? Commented Jan 28, 2019 at 14:06

6 Answers 6

2

Your logic is almost correct, but the issue is that you're providing a function to find() whereas you simply need to use a selector string:

$(".add__block").click(function() { var id = $(this).parent().find(".block__id").text(); console.log(id); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="col-12"> <span class="block__id">Block #1</span> Block title <span class="add__block">+</span> </div> <div class="col-12"> <span class="block__id">Block #2</span> Block title <span class="add__block">+</span> </div>

Sign up to request clarification or add additional context in comments.

Comments

1

I'm not very familiar with jQuery, but with vanilla Javascript this is very easy:

const blocks = document.querySelectorAll('.add__block'); for (const block of blocks) { block.addEventListener('click', (e) => { console.log(e.target.previousElementSibling.textContent) }) }
<div class="col-12"> <span class="block__id">{{$block->id}}</span> {{$block->title}} <span class="add__block">+</span> </div>

1 Comment

This is perfect.. thanks, but i have to accept the jquery version.
1

Another alternative is just looking for the sibling with prev method, which might be slightly faster than going to parent and then search from there.

$('.add__block').click(function(){ var id = $(this).prev('.block__id').text(); console.log(id); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="col-12"> <span class="block__id">Block #1</span> Block title <span class="add__block">+</span> </div> <div class="col-12"> <span class="block__id">Block #2</span> Block title <span class="add__block">+</span> </div>

Comments

0

Can you try like below:

$(".add__block").click(function(){ var id = $(".block__id").text(); console.log(id); }); 

1 Comment

Note that this selects all the .block__id elements, not just the one related to the clicked .add__block element.
0

On click you can find the parent of the .add__block element and find the relevant .block__id within the parent as follows,

$(".add__block").click(function(){ console.log($(this).parent().find(".block__id").text();); }); 

Comments

0

$('.add_block').prevAll('span')

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.