My task is to perform an adaptive layout, using JS + JQuery to write the entire below-listed unnumbered list into the value of a variable with the goal to place it after the <header> (I will show it with the surrounding tags):

 <header> <div class="centering"> <h1> Пример сайта </h1> <ul id="main-menu"> <li><a href="#">ПунктМеню1</a></li> <li><a href="#">ПунктМеню2</a> <ul class="sub-menu"> <li><a href="#">ПунктМеню2-1</a></li> <li><a href="#">ПунктМеню2-2</a></li> </ul> </li> <li><a href="#">ПунктМеню3</a></li> </ul> </div> </header> 

If you do this with .html("#main-menu") , then only children with respect to <ul> elements will be copied. Then I tried to use .parent :

 var MainMenuContents=$("#main-menu").parent().html(); 

However, together with the list, for some unknown reason, the title is also written into the variable. Can this be avoided? If possible, I ask you not to assign a class or identifier to the tag <header> (and I have several .centering .centering on my page).

    1 answer 1

    Oh, do not forget that jQuery only helps JS , not replacing it at all.
    The reason for your failure is simple: the ancestor for the list is the header , the div and h1 blocks are the neighbors.

     $(function(){ // Берём HTMLUListElement из коллекции jQuery // И используем встроенное свойство получения полного кода элемента console.info($('#main-menu')[0].outerHTML); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <header> <div class="centering"> <h1> Пример сайта </h1> <ul id="main-menu"> <li><a href="#">ПунктМеню1</a></li> <li><a href="#">ПунктМеню2</a> <ul class="sub-menu"> <li><a href="#">ПунктМеню2-1</a></li> <li><a href="#">ПунктМеню2-2</a></li> </ul> </li> <li><a href="#">ПунктМеню3</a></li> </ul> </div> </header> 

    • Thank you for your reply. Unfortunately, we were unable to google HTMLUListElement to such an extent as to understand how to apply it. Could you show how to write the above unnumbered list in the value of a variable? - Hokov Gleb
    • @GurebuBokofu is just the name of the DOM element for the list. var MainMenuContents = $('#main-menu')[0].outerHTML; . - user207618
    • Well, that’s the problem solved. Thank you very much for taking the time to answer this question! - Bokov Gleb
    • @GurebuBokofu, always please accept the answer as correct (ticked under the reputation of the answer). - user207618