I want to change ID="value"
with another id value from tag and I also want to change the value where this name used as target attribute value if there in code
$('div[id]').each(function() {
$(this).attr("id", "newValueWithRandomNumber")
// I can change only ID value
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="example1"> I can easily change ID name here </div>
<div id="example2"> I have to find dynamically where this ID used as target value </div>
<div data-bs-target="example2"> button </div>
<div data-*any="example2"> button </div>
<div *any="example2"> button </div>
2
Answers
I really don’t like this approach, but if you can’t alter the HTML to use classes and make your DOM references that way, you can scan the DOM for the string you wish to replace and replace all occurrences with
.innerHTML
. This approach could of course be customized to search just parts of the DOM rather than the whole thing.You can do this but it is not super fast so you want to limit the scope (not document or body for instance). Two examples but same functional result.
NOTE: Here I dealt with the potentially harder example of data attributes but a similar process could be done for other attributes.
Second example I added some CSS to show the NOT targeted attribute did not change value;
I put a LOT of comments and console logs in the first example:
Less noise, but same thing functionally.