Home > Blockchain >  Jquery: Give styling (padding) of the parent class based on the condition that the first child match
Jquery: Give styling (padding) of the parent class based on the condition that the first child match

Time:06-01

Parent Class: cmp-container There are two child classes - productmodelfootnotes footnotes

According to the sequence of the child I want to give padding as follows - If "productmodelfootnotes" child class comes first -> Apply padding=40px to the parent class (cmp-container) If "footnotes" child class comes first -> Apply padding=64px to the parent class (cmp-container)

CodePudding user response:

First of all, initialize your parent element

let parent = document.querySelector('.cmp-container')

Then add style, based on condition

let firstChild = parent.children[0];
if(firstChild.classlist.contains('productmodelfootnotes'){
    parent.style.padding = "40px";
} else if(firstChild.classlist.contains('footnotes')) {
    parent.style.padding = "64px";
}

CodePudding user response:

Consider the following.

$(function() {
  $(".cmp-container").each(function(i, el) {
    if ($("div:eq(0)", el).hasClass("productmodelfootnotes")) {
      $(el).addClass("shortpad");
    } else if ($("div:eq(0)", el).hasClass("footnotes")) {
      $(el).addClass("longpad");
    }
  });
});
.cmp-container {
  border: 1px solid blue;
  margin-bottom: -1px;
}

.cmp-container .footnotes {
  border: 1px solid red;
}

.cmp-container .productmodelfootnotes {
  border: 1px solid green;
}

.shortpad {
  padding: 40px;
}

.longpad {
  padding: 64px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >
    Product Note 1
  </div>
  <div >
    Foot Note 1
  </div>
</div>
<div >
  <div >
    Foot Note 2
  </div>
</div>
<div >
  <div >
    Product Note 3
  </div>
  <div >
    Foot Note 3
  </div>
</div>
<div >
  <div >
    Foot Note 4
  </div>
  <div >
    Product Note 4
  </div>
</div>

Using .each(), we can iterate over the DIV elements and check the order of the children. If they meet the specific condition, we can add a Class or apply a Style to that element.

See More: https://api.jquery.com/each/

I assign i as the Index and el as the Element. I then use a Find selector, $("div:eq(0)", el) which is the same as $(el).find("div").eq(0) where 0 represents the first item in the list or elements that is Found.

Using .hasClass() we can check if it is true or false, and perform a specific action based on the condition.

See More: https://api.jquery.com/hasClass/

I used an if / else if statement to check two conditions. This is in case another element may appear first that should not have any padding.

In the future, it is important to post a question with a Minimal, Reproducible Example.

  • Related