karan k
karan k

Reputation: 977

Accessing a particular element through DOM

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

Answers (4)

Ram
Ram

Reputation: 144729

$('label').siblings('span').attr('class');

http://jsfiddle.net/Cf9Qn/

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87083

Just try this:

$('label')
      .prev('span')  // get the previous span of label
      .attr('class');  // get class of the span.

DEMO

or

$('label')
      .siblings('span')  // get the previous span of label
      .first()
      .attr('class');  // get class of the span

DEMO

Upvotes: 1

Hadas
Hadas

Reputation: 10384

Use this:

var sibling = $('label').siblings('span').first();
var class = $(sibling).attr('class');

Upvotes: 1

Aeolun
Aeolun

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

Related Questions