Search code examples
jqueryjquery-selectorsdropdownpicker

Select niece and change siblings


I have this bootstrap (minimized) code.

<div id='DD_type' class="dropdown">
   <button class="btn" ></button>
   <span id='af'>Type</span>
   <ul class="dropdown-menu">
      <li> 
         I want this HTML(its more than text) in my button
      </li>
   </ul>
</div>

<div id='Another Dropdown' class="dropdown">
   <button class="btn" ></button>
   <span id='af'>Type</span>
   <ul class="dropdown-menu">
      <li> 
         I want this HTML(its more than text) in my button
      </li>
   </ul>
</div>

I want to fill the button with the first element in the li. What I now have is a static soluction.

$(function() {
   $('#DD_LayOut>button').html($('#DD_LayOut>ul>li').html())
}

However I would like to have a generic solution. (Yes I did some searching).

Mine is not working at all.

 $('.dropdown > button').html($(This).siblings('ul>li:first').html())

Could someone help me with this problem.

Thanks in advance!


Solution

  • To achieve this you can provide the html() method with a function as the scope of that function will be the button element which you can use to traverse the DOM to find the required li, something like this:

    $('.dropdown > button').html(function(i, h) {
        return $(this).siblings('.dropdown-menu').find('li:first').html();
    });
    

    Working example