Reputation: 49
Does anybody know how to select a specific class of an element. I have an element created in html. This element has two classes "n" and "s1" for example:
{<td class="n" class="s1" id=""><img src="gfx/football.png" /></td>}
Then in jquery I create another element (it's just a div). What I'm trying to do is: when the element above (td) is clicked I want to add same class (class s1) to my new <div>
. I simply need these two elements with the same class.
The code I'm using looks like this:
myDIVishere.addClass($(this).attr('class')
This line adds a class to my new div but as you can see above my $(this) --> <td>
has two classes. How to tell the program that I want to add second class (class="s1") and not the first one. I nearly forgot. I have 50 <td>
elements so I can't use the class name.
Upvotes: 0
Views: 103
Reputation: 8814
First, you have to fix your markup.
I tested in Opera and Chrome, and class="foo" class="bar"
is not valid.
It should be class="foo bar"
.
This considered, you can get the second class with the following:
var el = $('<a />', { class: 'foo bar' });
var classes = el.attr('class').split(' ');
var secondClass = classes[1];
Be sure to check secondClass for undefined before adding to another element, as this may lead to unexpected results.
Upvotes: 1
Reputation: 21810
when you are using that attribute information to identify an element, you really should use an ID, that way its unique.
if you can't / won't store it in the ID attribute, instead store s1
in a class, give it a separate and identifiable attribute... so you can grab it this way:
var specialValue = $('.myElement').attr('special-attribute');
$('.someOtherElement').addClass( specialValue );
but there, the use of addClass
would also be a waste of energy. you can literally keep using attributes at that point.
Upvotes: 0