Home Ask Login Register

Developers Planet

Your answer is one click away!

user1149168 February 2016

JQuery to find LI by text and UL by Class

I am working with a list in SharePoint 2013 that creates an unordered list dynamically on mouseover (the List item ECB for those familiar with SharePoint).

The class name that is given has spaces added after at, 1 additional space for each menu item. I'm not sure if this affects the class property value in jquery so that is why I'm using the begins with notation.

I am needing to hide several menu items and I'm not getting alerts in my debug so I'm thinking my syntax is off.

I'm using this:

if($('ul[class^="ms-core-menu-list"] li[text="View Item"]') ! == null) {
} else {
  alert('no F');

I do not get alerts so either my syntax is wrong and I need assistance with that or the menu item isn't created when this code executes, in which case I'm wondering how it is possible to get at these menu items using jquery as I'm unable to deploy code in my environment. I've looked at a number of blogs over the past few days but nothing recommended comes close to working for me.

Thank you


nAviD February 2016

Use this :

if($('ul.ms-core-menu-list li[text="View Item"]').length==0)

Note that JQuery always returns a JQuery object which is not null.

twernt February 2016

If you're trying to find out if the page contains any li tags that with the text "View Item" that are children of ul tags with the class "ms-core-menu-list" you can use this selector:

$('li:contains("View Item")', $('ul.ms-core-menu-list')).length;

In the context of your example:

if($('li:contains("View Item")', $('ul.ms-core-menu-list')).length) {
} else {
  alert('no F');

Atticus February 2016

The thing to remember about jQuery selectors is that they will always return an object. Even if you don't find anything, you are still given the jQuery API to call things like .hide(), .show(), etc. You won't get an error if you haven't selected anything when calling a jQuery method, you just won't have anything selected for the calls to act upon.

What you can do to infer if any elements are selected is by treating it like the psuedo-array that it is -- you can use .length.

In your case,

if ($('ul.ms-core-menu-list li[text="View Item"]').length > 0) {
} else {
  alert('no F');

Post Status

Asked in February 2016
Viewed 2,528 times
Voted 7
Answered 3 times


Leave an answer

Quote of the day: live life