ech
ech

Reputation: 3

Select children in JavaScript because I can't use jQuery

I'm using jQuery to find out if there is an li with the attribute of data-val="-1" inside the #mainNavigation div. In jQuery this works fine, but I need to do the same thing in JavaScript. What I can't figure out is how to drill down the way it's done using selectors in jQuery.

if($('#mainNavigation ul li ul li[data-val="-1"]')){
   $("#mainNavigation").css("padding-left" , "10px");
};

<div id="mainNavigation">
    <ul>
        <li>
            <ul>
                <li data-val="-1">Title</li>
            </ul>
        </li>
    </ul>
</div>

Upvotes: 0

Views: 100

Answers (1)

Blue Skies
Blue Skies

Reputation: 2975

You can use .querySelector():

if (document.querySelector('#mainNavigation ul li ul li[data-val="-1"]')){
   // ...
}

Or if you don't need to be so specific about the level, then this:

if (document.querySelector('#mainNavigation li[data-val="-1"]')){
   // ...
}

Or without using querySelector:

var lis = document.getElementById('mainNavigation').getElementsByTagName("li");
var found = false;
for (var i = 0; i < lis.length; i++) {
    if (lis[i].getAttribute("data-val") === "-1") {
        found = true;
        break;
    }
}

if (found) {
    // ...
}

Upvotes: 1

Related Questions