Skip to content

Select element only if it is immidiatly followed by another element

In JavaScript if I get all li elements with getElementsByTagName(“li”); how do I then only select li elements that are directly followed by span? For example:

  <li>test<span style="color: red;"> A</span>dfg</li>
  <li><span style="color: red;">Test B</span>dfg</li>

Here I want only to select 2nd li because it is followed by span immediately and not the first one because it opens with text.



the function below collects an li element(how ever way you get the element), and checks if its first child element is a span and returns it

function checkElem(elem) {
    // check if the element is an li element
    if (elem.tagName != "LI") {
        // if its not, return false
        console.log("The element passed is not an li element");
        return false;
    } else {
        // get the first child element of the li
        var firstChild = elem.firstChild;

        // check if the first child is a span tag
        if (firstChild.tagName == "SPAN") {
            // return the li element
            return elem;
        } else {
            // else return false
            console.log("List item's first element is not a span");
            return false;

So u can use like this

var liElements = getElementsByTagName("li");

liElements.forEach(li => {
    var myLi = checkElem(li);
    if(myLi != false){ = "30px";