Reputation: 977
I'm having trouble with DOM. I'm trying to access the class of a particular <span>
element.
HTML:
<span><span class="abc">*</span><label for="sometext"></label></span>
I want to access the class 'abc' of the <span>
element, and I have the <label>
element with me.
Here's what I'd done:
var parent=$(label[0]).parent();
var class=$(parent[0]).childNodes[0].attr("class");
EDIT:The previous sibling of the appears to be some Text node!!..Don't know why
Upvotes: 0
Views: 71
Reputation: 87083
Just try this:
$('label')
.prev('span') // get the previous span of label
.attr('class'); // get class of the span.
or
$('label')
.siblings('span') // get the previous span of label
.first()
.attr('class'); // get class of the span
Upvotes: 1
Reputation: 10384
Use this:
var sibling = $('label').siblings('span').first();
var class = $(sibling).attr('class');
Upvotes: 1
Reputation: 756
If you are using jQuery, you can simply use:
var classes = $(label[0]).prev().attr('class');
I'd recommend not naming your 'class' variable 'class' as it is a reserved word in javascript.
Upvotes: 2