This is heavily trimmed down source code from a webpage I’m working on right now.
<!--// GRID ENTRY //-->
<li class="entry" id="sjDDulC8wt">
<div class="entry_actions">
<ul class="entry_actions">
<li class='have_it'>
<a href='javascript: haveItem("name", "id", "none")' target='_self' title='Have It' class='have_it'>%</a></li>
</ul>
</div>
</li>
Inside the haveItem() function I’m trying to change the class of the <a> element from ‘have_it’ to ‘have_it selected’ to change the appearance of the element. The reason for the id is because I have dozens of these elements on the page. The javascript I’m currently using is:
var targetA = document.getElementbyID(sjDDulC8wt).getElementsbyTitle("Have_it");
targetA.removeClass("have_it").addClass("have_it selected");
When I click the link, the haveItem() function runs, but it doesn’t change the class. How can I change my script so that clicking the link will change the class?
I am assuming you are using jQuery since you are using
removeClass()andaddClass. Otherwise, I would recommend you link to jQuery so that the code below works, or stick with only JavaScript.For future reference, here are some things about your code that you can improve:
getElementById()accepts the id of the element you want to retrieve as a string. Basically, you should wrap your ID in'or"Have It, while your JavaScript hasHave_it.Have_Itis not the same thing asHave_it. Be careful with this when you try to get elements by ID.have_it selectedactually has both thehave_itclass and theselectedclass. Therefore it not necessary to removehave_itand then addhave_it selected– you can go straight to adding theselectedclass.getElementbyTitle()does not currently exist in JavaScript. Also, be careful again about capitalization. Typically, the first letter of every word in a function is capitalized. Thus, if it did exist it would be calledgetElementByTitle()(notice theBinstead ofb).