Reputation: 15
How to add value from the title to the value of the class to the same element with jQuery?
For Example, I will add word "new1" to title name for picture of 1.jpg. And then in class of picture 1.jpg it will get class of "new1" by jQuery.
<script>
$( document ).ready(function() {
$("[title*='animotion']").addClass('new1',function(){
$(this).parent().css('overflow','visible');
str=$(this).attr("title");
str=str.replace('animotion ','');
return str}).removeAttr('title');
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
So if I add "animotion new23" I have in class tag only new1. So how can I edit this code that new 23 will be in class?
======================================================================= NEW Question. So after that how to add css class to new1 to style.css?
Upvotes: 0
Views: 83
Reputation: 9644
Since you want to use title value to add classes, than you can do it simply this way:
$(document).on('ready', function() {
$("[title*='animotion']").addClass(function(){
$(this).parent().css('overflow','visible');
return $(this).attr('title');
}).removeAttr('title');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<p><img src="http://placehold.it/350x150" title="animotion newClass new1" /></p>
jQuery addClass method accepts class name(s) or a function. In both cases the value must be a string that contains:
One or more space-separated classes to be added to the class attribute of each matched element.
Upvotes: 0
Reputation: 33409
As far as i know, .addClass()
takes either a string or a function, not both. Try chaining calls of .addClass()
:
$( document ).ready(function() {
$("[title*='animotion']").addClass('new1').addClass(function(){
$(this).parent().css('overflow','visible');
str=$(this).attr("title");
str=str.replace('animotion ','');
return str}).removeAttr('title');
});
Upvotes: 0
Reputation: 453
$("[title*='animotion']").addClass(function(){
// add the string that you want to applear and concatenate it with the title attribute of the object and return it as a parameter to addClass;
return 'new1'+$(this).attr('title');
});
Upvotes: 1