0

I have a quite easy jquery question that I can't get right, when clicking on a link I need to insert some text in the right p (the table row before).

This is the html:

<table>
<tr>
    <td>
        <p class='MyClass'>NOT HERE</p>
    </td>
</tr>
<tr>
    <td>
        <p class='MyClass'>NOT HERE</p>
    </td>
</tr>
.
. //Many table rows
.
<tr>
    <td>
        <p class='MyClass'>HERE I WANT TO INSERT THE TEXT</p>
    </td>
</tr>
<tr>
    <td>
        <div>
             <a href='#' class='MyLink'>insert text</a>
        </div>
    </td>
</tr>
</table>

This is the jquery:

$('.MyLink').click(function() {
    HOW CAN I MAKE SOME TEXT GO INTO THE RIGHT <p> HERE?
});
1
  • what is the "RIGHT <p>"? Dec 11, 2009 at 22:12

3 Answers 3

1
$(this).closest('tr').prev('tr').find('.myClass').html('text here');

(untested)

1
  • Just a note: closest() is new in jQuery 1.3, you probably need to do some more element traversal if you can't use the new version.
    – Jay Zeng
    Dec 11, 2009 at 23:41
0

One real easy way would be to give:

<p class='MyClass'>HERE I WANT TO INSERT THE TEXT</p>

a class or ID, so that you could reference it directly. For instance:

<p id="insertHere" class='MyClass'>HERE I WANT TO INSERT THE TEXT</p>

Then you could just do something like:

$('.MyLink').click(function() {
    $("#insertHere").text($("#insertHere").text() + "SOME TEXT YOU WANT TO INSERT");
});

If you want to specify the "insert into" P some other way, just change the selector from "#insertHere" to one that defines which P you want to insert in to.

Also, I think:

$('.MyLink').click(function() {
    $("#insertHere").append("SOME TEXT YOU WANT TO INSERT");
});

will work too (and be shorter), but I'm not 100% certain (so test first).

0
$(this).parents('tr:first').prev('tr').find('.myClass').html("The Text that you want");

.parents walks up the dom to the first tr above your link, then prev('tr') takes you to the previous row, and finally the find searches down the tr for all elements that have the ".myClass" class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.