Reputation: 7087
I want to find and replace a piece of text in an onCLick
event in the DOM. I tried jQuery find
contains
and may more but none of them worked. Can you please help. There are multiple onClick events with the same 'class' so I want to first look for Click OK to cancel this booking.
and THEN replace it with `he New Piece Of Text Here'
This is what I have
`<a href="#" class="replaced_btn" onclick="return confirm('Click OK to cancel this booking.');"></a>`
I want it changed to this
<a href="#" class="replaced_btn" onclick="return confirm('The New Piece Of Text Here');"></a>
Upvotes: 2
Views: 525
Reputation: 6264
var elem = '<a href="#" class="replaced_btn" onclick="return confirm(' + 'Click OK to cancel this booking.' + ');"></a>';
elem = elem.replace("Click OK to cancel this booking.", "The New Piece Of Text Here");
alert(elem)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
OR
$("a").click(function() {
var elem = $(this).attr('onclick');
elem = elem.replace("Click OK to cancel this booking.", "The New Piece Of Text Here");
$(this).attr('onclick',elem);
alert($(this).attr('onclick'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="replaced_btn" onclick="return confirm(' + 'Click OK to cancel this booking.' + ');"> Test </a>
Upvotes: 1
Reputation: 388446
You can use the attribute contains filter
jQuery('.replaced_btn[onclick*="Click OK to cancel this booking."]').attr('onclick', function(i, value) {
return value.replace('Click OK to cancel this booking.', 'The New Piece Of Text Here')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="replaced_btn" onclick="return confirm('Click OK to cancel this booking.');">test</a>
jQuery('.replaced_btn[onclick="return confirm(\'Click OK to cancel this booking.\');"]').attr('onclick', function(i, value) {
return value.replace('Click OK to cancel this booking.', 'The New Piece Of Text Here')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="replaced_btn" onclick="return confirm('Click OK to cancel this booking.');">test</a>
Upvotes: 1