Uzair Xlade Uzair Xlade - 7 months ago 55
HTML Question

jquery selector li:selected

I am using simple jquery selector but unfortunately didn't get the required result.
my code is:

$(document).ready(function() {
var displayName = $('.divclass').find('ul').find('li:first').text();
if ($('.divclass').find('ul').find('li:selected').length) {
displayName = $('.divclass').find('ul').find('li:selected').text();

<script src=""></script>
<div class="divclass">
<button data-toggle="dropdown" class="btn btn-primary dropdown-toggle" aria-expanded="true">
<span class="caret"></span>
<ul class="dropdown-menu">
<a href="#">sometext1</a>
<li selected="selected">
<a href="#">sometext2</a>
<a href="#">sometext3</a>

I called it on document.ready. It executes but did not give me the proper result, what I am doing wrong to select the
with selected attribute.


:selected has a specific meaning: An option element that is currently selected. Perhaps somewhat counter-intuitively, that selected state is not reflected in an attribute (just the default) and again, it only applies to option elements.

selected isn't a valid attribute for li elements. You could either use data-selected for your own flag attribute, or a class.

If you used data-selected, you'd use [data-selected] in the selector:

<li selected="selected">

...and then add/remove the attribute as appropriate.

If you use a class instead, it's a class selector:

<li class="selected">

...and then you add/remove the class as appropriate.