2
var cName = ($(".myclass").next().attr('class'));
alert(cName);

if (cName == "c1") {

$("#Output").addClass("green");
$("#Output").removeClass("red");

} else {

$("#Output").addClass("red");
$("#Output").removeClass("green");
}

<p class="myclass">If you click on me, I will disappear.
<span class="c1"></span>
<span class="c2"></span>
<span class="c3"></span>
<span class="c4"></span>
<div class="d1"></div>
<div class="d2"></div>
<div id="Output" style="width:25px; height:25px;"></div>
</p>

I am trying to get the .classname of the first span element. Why is jquery not fetching the next span element .classname ? Please help.

imsheth
  • 31
  • 2
  • 18
  • 36
PRANAV
  • 1,009
  • 5
  • 16
  • 36

3 Answers3

1

next() is getting the sibling of the p element, not the first child. To get the first child, do

var cName = $(".myclass").children().first().attr('class');

console.log($(".myclass").children().first().attr('class'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p class="myclass">If you click on me, I will disappear.
  <span class="c1"></span>
  <span class="c2"></span>
  <span class="c3"></span>
  <span class="c4"></span>
  <div id="Output" style="width:25px; height:25px;"></div>
</p>
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
  • Thanks Ammar, how to get class of first div child ? inside .myclass div there is different tags. i need to get 1st div element class name. – PRANAV Jun 25 '15 at 05:50
0
var cName =($(".myclass").next().attr('class'));

Here next() element will get the next <p> sibling and not the span element..If you need to get next span element use this

var cName =$(".myclass span:first-child").attr('class');
Nagaraj S
  • 13,316
  • 6
  • 32
  • 53
0

It is not a proper way to define div tag inside p tag. And hence you are unable to access those child div elements.The opening div tag will automatically close the p tag. Because end tag of <p> elements are optional know.

It means <p> tags can contain only the inline elements.

<!ELEMENT P - O (%inline;)*            -- paragraph -->

Block elements are not allowed to define inside the <p> elements.

Please refer the following link, which describes about the block and inline elements in detail:

http://www.w3.org/TR/html401/struct/text.html#h-9.3.1

And also refer the following stack overflow links which has been already discussed:

Putting <div> inside <p> is adding an extra <p>

Why <p> tag can't contain <div> tag inside it?

Hope this helps you....

Community
  • 1
  • 1
John R
  • 2,741
  • 2
  • 13
  • 32