I have this jQuery code:
$(".q-block-container").prev(".sub-block-container").css("border-bottom","none");
I need a pure JavaScript equivalent, whereby I can select the previous sibling ONLY if it matches the selector (in this case .sub-block-container
).
For example, lets say I have a list and each item in the list has a border-bottom
style. Depending in what the sibling is before a particular list item, that should determine whether or not the border should be applied:
<ul>
<li class="q"></li>
<li class="q"></li>
<li class="q"></li>
<li class="s"></li>
<li class="s"></li>
<li class="q"></li>
<li class="s"></li>
<li class="q"></li>
</ul>
In this example, a border must NOT appear on the previous sibling <li>
element if:
the element is q and the previous sibling is s
the element is s and the previous sibling is q
the element is s and the previous sibling is s
Try this if your element .sub-block-container
will have only that single class.
var elem = document.getElementsByClassName("q-block-container");
for (i=0; i<elem.length; i++) {
var prev = elem[i].previousElementSibling;
if (prev.className == "sub-block-container") {
prev.style.borderBottom = "none";
}
}
If your element may have more than one class, use this instead:
var elem = document.getElementsByClassName("q-block-container");
for (i=0; i<elem.length; i++) {
var prev = elem[i].previousElementSibling;
if (prev.classList.contains("sub-block-container")) {
prev.style.borderBottom = "none";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With