Uzair Xlade Uzair Xlade - 11 days ago 6
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();
}
$('divclass').find('button').html(displayName);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divclass">
<button data-toggle="dropdown" class="btn btn-primary dropdown-toggle" aria-expanded="true">
sometext
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li>
<a href="#">sometext1</a>
</li>
<li selected="selected">
<a href="#">sometext2</a>
</li>
<li>
<a href="#">sometext3</a>
</li>
</ul>
</div>





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

Answer

: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">
...find('ul').find('li[data-selected]').length...

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

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

<li class="selected">
...find('ul').find('li.selected').length...

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