user1551482
user1551482

Reputation: 529

Selecting a specific children element using jquery?

I want to select specific children elements from the $el.html, there are two types of children elements, one with <span>....</span>, the other has a span class <span class = "special">..</span> for example:

var orig = $(".example").html()
    ,$el = $(".example")
    ,text = $.trim($el.text())
    ,words = text.split(" ")
    ,html = "";

for (var i = 0; i < words.length; i++) {
    if (words[i] === "senior")
    html += "<span class='special'>" + words[i] + ((i+1) === words.length ? "" : " ") + "</span>";
    else
        html += "<span>" + words[i] + ((i+1) === words.length ? "" : " ") + "</span>";
   };
$el.html(html).children().hide().each(function(i){
 // if $('span.special')
  $(this).delay(i*200).fadeIn(700);
 // else (normal span)
  $(this).delay(i*600).fadeIn(900);
}).promise().done(function(){
       $('.example:first').html(orig)
    })

How can I tell the difference between the spans with and without the class within my 'each' call?

the working demo is here : http://jsfiddle.net/6czap/15/

Upvotes: 2

Views: 233

Answers (1)

Zeta
Zeta

Reputation: 105955

I believe you're looking for .hasClass:

$el.html(html).children().hide().each(function(i){
  if($(this).hasClass('special'))
      $(this).delay(i*200).fadeIn(700);
  else
      $(this).delay(i*600).fadeIn(900); 
}).promise().done(function(){
       $('.example:first').html(orig)
});

Demo

However, if you only want to fade in the .special elements use

$el.html(html).children('.special').hide().each(function(i){
  if($(this).hasClass('special'))
      $(this).delay(i*200).fadeIn(700);
}).promise().done(function(){
       $('.example:first').html(orig)
});

instead (see .children, demo).

Upvotes: 3

Related Questions