Eamorr
Eamorr

Reputation: 10012

jQuery - search by attribute values and change all the values

I have the following sort of HTML:

<tr>
    <td data-pk="-999">test1</td>
    <td data-pk="-999">test1</td>
    <td data-pk="-999">test2</td>
    <td data-pk="-999">test3</td>
    <td data-pk="-999"><a data-pk="-999">test4</a></td>
</tr>

I want to change all the -999's to 24 (say).

Can anyone suggest some clean and quick jQuery that recursively traverses the DOM (from the tr) and changes all the -999's?

Basically, I have a table where I add a new temporary row to my site's front-end. When the user saves this row, a new id (24 in this case) is generated. "-999" is a flag for my backend to tell it that a new entry is required in the database and that an id should be returned.

Upvotes: 0

Views: 48

Answers (1)

AmmarCSE
AmmarCSE

Reputation: 30557

Use attr()

$('[data-pk="-999"]').attr('data-pk', 24);
[data-pk="24"] {
  color:green;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
<tr>
    <td data-pk="-999">test1</td>
    <td data-pk="-999">test1</td>
    <td data-pk="-999">test2</td>
    <td data-pk="-999">test3</td>
    <td data-pk="-999"><a data-pk="-999">test4</a></td>
</tr>
</table>

Upvotes: 3

Related Questions