Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure javascript alternative for jQuery .prev()?

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

like image 597
JoeTidee Avatar asked Apr 29 '17 23:04

JoeTidee


1 Answers

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";
    }
}
like image 108
Abraham Murciano Benzadon Avatar answered Sep 22 '22 02:09

Abraham Murciano Benzadon