WatsMyName
WatsMyName

Reputation: 4478

Detect if childelement immediately comes after starting of parent div or not

I m running into little trouble. I have following HTML code

<div id="parentdiv">
        This is test immediately in a parent div, not within child element
        many more text comes. 
        <p class="childelement">This is under child element</p>
        Another bunch of text also comes here
    </div>

The p tag with class childelement may occur one or more time anywhere within parentdiv. All I want to do is detect one of the either two situations below:-

  1. Detect if childelement immediately comes after starting of parent div or not.
  2. Detect if there is any text before the childelement

What i basically want to do is, if childelement satisfies point 2, then I will append margin-top style to this element, otherwise not.

What I tried is

$('.childelement:gt(0)').css({'margin-top':'5pt'});

This works well for all childelement in a parent div,if there is childelement right after starting tag of parent div. But if I remove this first occurrence of childelement, the margin-top css is lost in second childelement because after removing first element, its index becomes 0 .

Just a hint would be well enough for me.

Any help will highly be appreciable

Upvotes: 4

Views: 79

Answers (1)

Ram
Ram

Reputation: 144689

You can use .filter() method and read the previousSibling property the of the element, note that I have used $.trim() to exclude textNodes that don't have visible characters, if you want to include those nodes, you can remove the method.

$('#parentdiv .childelement:first-child').filter(function() {
    return this.previousSibling 
           && $.trim(this.previousSibling.nodeValue).length;  
}).css({'margin-top':'5pt'});

http://jsfiddle.net/Tcb4s/


An update made by @LoVeSmItH:

$('#parentdiv .childelement:first-child').filter(function() {
     var sit=this.previousSibling && $.trim(this.previousSibling.nodeValue).length;
     if ($.trim(sit)!="") {
         return sit;
     } else {
        $('.childelement:gt(0)').css({'margin-top':'5pt'});
     }
}).css({'margin-top':'5pt'});

My suggestion based on the edit:

var $child = $('#parentdiv .childelement'),
    $first = $child.filter(':first-child').filter(function() {
               return this.previousSibling 
                      && $.trim(this.previousSibling.nodeValue).length;  
             });

if ($first.length) $first.css({'margin-top':'5pt'});
else $child.not(':first').css({'margin-top':'5pt'});

Upvotes: 3

Related Questions