Главная страница  /  Занятия  /  #18  /  Навигация по элементам в jQuery

Навигация по элементам в jQuery

Задание:

Продемонстрировать, как осуществляется навигация по элементам html-документа в jQuery.

html-документ (index.html):

   <!DOCTYPE html>
   
   <html lang="ru">
   
    <head>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Навигация по элементам в jQuery</title>
     <link rel="stylesheet" href="styles.css">
     <script src="/js/jquery-3.6.0.min.js"></script>
     <script src="scripts.js"></script>
    </head>
   
    <body>
     <ul class="menu">
      <li class="punkt1">Пункт 1</li>
      <li class="punkt2">Пункт 2
       <ul class="submenu">
        <li>Подпункт 2.1</li>
        <li>Подпункт 2.2</li>
       </ul>
      </li>
      <li class="punkt3">Пункт 3
       <ul>
        <li>Подпункт 3.1</li>
        <li>Подпункт 3.2</li>
       </ul>
      </li>
     </ul>
   
     <button id="myButton">Нажми меня</button>
    </body>
   
   </html>

CSS–разметка (styles.css):

   #myButton		{ width: 140px; height: 30px; border: 1px solid #d0d0d0; background-color: #f0f0f0; color: #000000; outline: none; margin-top: 20px; }

JS–скрипты (scripts.js):

   window.onload = function()
   {
    document.getElementById('myButton').onclick = function()
    {
     var firstLists = $('li').children('');
     firstLists.each(function(index, element)
     {
      alert('Children:\n'+element.innerHTML);
     });
   
     var secondLists = $('li').children('.submenu');
     secondLists.each(function(index, element)
     {
      alert('Children:\n'+element.innerHTML);
     });
   
     var thirdList = $('li').closest('ul.submenu');
     thirdList.each(function(index, element)
     {
      alert('Closest:\n'+element.innerHTML);
     });
   
     var fourthLists = $('li.punkt1').next();
     fourthLists.each(function(index, element)
     {
      alert('Next:\n\n'+element.innerHTML);
     });
   
     var fifthLists = $('li.punkt2').prev();
     fifthLists.each(function(index, element)
     {
      alert('Previous:\n\n'+element.innerHTML);
     });
   
     sixthLists = $('.punkt2').siblings();
     sixthLists.each(function(index, element)
     {
      alert('Siblings:\n\n'+element.innerHTML);
     });
   
     var seventhLists = $('.menu').parent();
     seventhLists.each(function(index, element)
     {
      alert('Parent:\n\n'+element.tagName);
     });
    };
   };

Результат:

Результат выполнения задания можно посмотреть здесь.