0

I am using the below code to change a class name of a button. However, I only want to do this for one button with the text 'Upload' and not another button that says 'Upload Database'.

Is it possible to change this from a 'Contains' to an exact match only?

<script> $( ".sitebutton:contains('Upload')" ).addClass('siteButton2').removeClass('sitebutton'); </script> 
1
  • There is no way to target it without using the text? Basically you would need to use filter since there is no way to do an exact match Commented Aug 9, 2017 at 14:18

5 Answers 5

2

You cannot do this with :contains as it's a 'hungry' match. An alternative is to use filter(), where you can do an exact match:

$('.sitebutton').filter(function() { return $(this).text().trim() == 'Upload'; }).toggleClass('siteButton2 sitebutton'); 

If possible, a much better solution would be to just put an id or class on the required button element and select via that.

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

Comments

0

Just use a jQuery filter on the elements:

$('.sidebutton') .filter((i, e) => $(e).text() === 'Upload') .addClass('sideButton2') .removeClass('sideButton'); 

You might need to trim the text, as there could be some extra whitespace floating around.

2 Comments

e would be the element, as there is no event firing in this context.
e is his second argument to filter method
0

You can use .filter() to check the .textContent of the element, :contains() checks if the text is included within the .textContent or .innerText in any form by using .indexOf() internally

$(".sitebutton").filter(function(i, el) { return el.textContent === "Upload" }) .removeClass('sitebutton') 

Comments

0

I think you're generally making it harder on yourself, but you can do something like this:

$(".sitebutton.Upload").not(".Database").addClass('siteButton2').removeClass('sitebutton'); 

Comments

0

Just put a specific id for the button and then call the needed code to change the class.
Check this Plunker

This is the code
HTML:

 <input type=button id="upload" value="Upload" class="sitebutton"> <input type=button id="uploaddb" value="Upload Database" class="sitebutton"> 

Script

 $('#upload').click(function() { $('#upload').addClass('siteButton2').removeClass('sitebutton'); }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.