Reputation: 7969
i want to replace class me to old when user clicks on a tag, i want to do that only with .replace function. My purpose to learn how replace method work. But the function which i have made not working.
<head>
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
$('a').click(function(){
$(this).attr('class').replace('me','old')
})
})
</script>
</head>
<body>
<a href="#" class="me">click</a>
</body>
Upvotes: 0
Views: 4786
Reputation: 17333
Try this instead:
<head>
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
$('a').click(function(){
var theclass = $(this).attr('class');
theclass = theclass.replace('me', 'old');
$(this).attr('class', theclass);
})
})
</script>
</head>
<body>
<a href="#" class="me">click</a>
</body>
That should do the trick. JSFiddle Link
Upvotes: 0
Reputation: 9080
$('a').click(function(){
$(this).replaceWith('<a href="#" class="old">click</a>');
});
I have created a bin with the solution on http://codebins.com/codes/home/4ldqpco
Upvotes: 0
Reputation: 70523
replace is not a jQuery function it is a function of string. You can read more about replace here. To use replace, you can read the attribute as a string, replace the contents of the string and then add the attribute back.
I don't think it is the best way to do this if you have jQuery loaded. You can use the jQuery utility designed to do these manipulations, like so:
$(this).toggleClass('me old');
This will turn on and off (toggle) both those class names. In effect it will switch from one to the other.
Docs:
http://api.jquery.com/toggleClass/
Upvotes: 3
Reputation: 144689
you are getting the class and it doesn't effect the class attribute, you can replace the string then set it to the element:
$('a').click(function(){
var cls = $(this).attr('class').replace('me','old')
$(this).removeClass('me').addClass(cls)
})
})
Upvotes: 2