Juliver Galleto
Juliver Galleto

Reputation: 9047

get to the specified parent element and then find the specified child

I have this HTML structure

<div class="parent_wrapper">
    <div class="child_element_one">
    </div>
    <div class="child_element_two">
        <p></p>
    </div>
    <div class="child_element_three">
        <a href="#">Click to test</a>
    </div>

and the script that I tried to work with it (my attempt so far)

$('.child_element_three a').click(function(e){
    $(this).parents('parent_wrapper').find('.child_element_two p').text("added to the div that has a class of child_element_two paragraph");
});

Problem: added to all div that has a class of child_element_two paragraph, what I want is only add text to the .child_element_two paragraph of the same group that has the current triggered link or the current group of the click link. How to do that?

Upvotes: 1

Views: 44

Answers (4)

Leo Silence
Leo Silence

Reputation: 1192

 $('.child_element_three a').click(function(e){
     $(this).parents('.parent_wrapper').find('.child_element_two p').text("added to    the div that has a class of child_element_two paragraph");
 });

U missing the. in parents('.parent_wrapper').

Upvotes: 1

Yangguang
Yangguang

Reputation: 1785

you can try:

$('.child_element_three a').click(function(e){
    $(this).parent().find('.child_element_two p').text("added to the div that has a class of child_element_two paragraph");
});

Upvotes: 0

renakre
renakre

Reputation: 8291

I think you can use .siblings in this task:

$('.child_element_three a').click(function (e) {
     $(this).parent().siblings('.child_element_two').find('p').text("added to the div that has a class of child_element_two paragraph");
});

DEMO: https://jsfiddle.net/udzdnh11/2/

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388436

You are missing the class selector in parent_wrapper, you have used it as a element selector.

Also change .parents() to closest() since you want only the first parent matching the selector

$(this).closest('.parent_wrapper').find('.child_element_two p').text("added to the div that has a class of child_element_two paragraph");

Demo: Fiddle

Upvotes: 2

Related Questions