I'm a little stuck here. I have a ul
menu of links. When a user selects from this list, I'm calling up content from another page with ajax. I want to grab a data attribute (data-flag
) from the selected anchor and add that attribute as a class to the div that holds the ajax content (#fourteen
). The adding class piece is working fine. However, when a new item is selected from the ul
menu, I can't seem to remove the other classes from the content div. With each click, it just adds more classes.
Here's my code.
<ul id="langtest" class="tp_lang2">
<li><a href="http://myurl.com/14-languages" data-flag="us" data-lang="English">English</a></li>
<li><a href="http://myurl.com/zh/14-languages" data-flag="cn" data-lang="Chinese (Simplified)">中文(简体)</a></li>
<li><a href="http://myurl.com/nl/14-languages" data-flag="nl" data-lang="Dutch">Nederlands</a></li>
<li><a href="http://myurl.com/fr/14-languages" data-flag="fr" data-lang="French">Français</a></li>
</ul>
<div id="fourteen" class="cn">
<div id="content">
<div class="main-content">Content being served up here.
</div>
</div>
</div>
<script>
jQuery("ul#langtest li a").click(function() {
jQuery('#fourteen').load($(this).attr("href") + " #content");
jQuery('#fourteen').removeClass.not(this).attr("data-flag");
jQuery('#fourteen').addClass($(this).attr("data-flag"));
return false;
});
</script>
You just need to remove all class in the element like so :
// remove all class
jQuery('#fourteen').removeClass();
// then add class name with data flag selected anchor only
jQuery('#fourteen').addClass($(this).attr("data-flag"));
DEMO(inspect element to see the class actually added & removed)