Tom
Tom

Reputation: 30698

Jquery: How to affect parent WHILE not children?

Is there a way to not affect children that are inside a parent when the parent is being changed?

<p>old text <a class="mylink">old link text</a></p>

$("a.mylink").click(function() {
        $(this).parent().text("new text for p");
        $(this).text("new link text for a");
    });
});

The above seems to get rid of the link text completely. I'd basically like to be able to change both texts when the click happens.

Thank you.

Upvotes: 0

Views: 701

Answers (2)

Hai Lu
Hai Lu

Reputation: 121

You can try this trick. It works

 $("a.mylink").click(function() {
       $(this).parent().html("new text for p" + $(this).text("new link text for a").html());
   });

Upvotes: 1

poke
poke

Reputation: 387557

Not a JQuery solution, but this works:

$("a.mylink").click(function() {
    $(this)[0].previousSibling.nodeValue = "new text for p";
    $(this).text("new link text for a");
});

Upvotes: 2

Related Questions