0

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>
ech
  • 3
  • 1

1 Answers1

1

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) {
    // ...
}
Blue Skies
  • 2,935
  • 16
  • 19
  • The 3rd option worked for me, thanks! Aren't the first two options using a jQuery selector by using #mainNavigation? – ech Nov 14 '13 at 18:16
  • @ech: No, they're using a Selectors API selector. This is native JavaScript code, not jQuery. It's what jQuery uses under the hood. – Blue Skies Nov 14 '13 at 18:40