0

I have two tables

 <table>
     <tr>
       <td class="myclass" data-date="2015-07-09"> Some text </td>
     </tr>
 </table>

 <table>
    <tr>
       <td data-date="2015-07-09"> Text </td>
    </tr>
 </table>

What I want to do is:

Firstly take the class 'myclass' and add to it one new class 'newclass' . I can easily do it by $('.myclass').addClass('newclass');

Secondly I want to search the DOM if there is a < td > which has the same data-date with the .myclass < td > and add also to the newly found < td > the .newclass

Thank you in advance

4 Answers 4

3

You can use:

 $('td[data-date='+$('.myclass').data('date')+']').addClass('newclass');

This will satisfy the both condition you are looking for. i.e. adding class to both the td elements.

$('.myclass').data('date') will get the date for myclass element. and attribute value selector to target all the td elments that have same data as that of myclass including myclass itself.

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

1 Comment

Oh, yeah, it looks great :) There is no need to assign classes differently for two tables.
1

You could simply do:

$('.myclass').each(function () {
    $('td[data-date="' + $(this).attr('data-date') + '"]').addClass('newclass');
}):

This will add the new class to each element with the same data-date, including the original one with myclass

Also, this would work fine even if you have multiple rows with a myclass - assuming your question was made more basic than your actual need.

Comments

0

Try this

$("td[data-date='2015-07-09']").addClass('myClass');

Comments

0

You can make it more simple if you give an id to your tables.
Like first-table-name and second-table-name.

In this case you will be able to do this with this code:

$("#first-table-name .myclass").each(function() {
    $(this).addClass("newClass");
    $("#second-table-name td[data-date='" + $(this).data('date') + "']").addClass("newClass");
});

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.