I have a fixed wp sub-menu list that looks something like this:
<ul style="display:flex">
<li ><a>Treatment Trials</a></li>
<li ><a>Alzheimer’s</a></li>
<li ><a href="">Asthma</a></li>
<li ><a>COVID-19 Treatment</a></li>
<li ><a>COPD</a></li>
</ul>
I'd like to wrap the first 3 and the last 2 elements into 2 <div >
elements so that they make two different columns side-by-sidy.
This content is not editable by the way, i can only add classes to li tags.
I have tried jQuery like this:
var open1col='<div >';
var close1col='</div><div >';
var close2col='</div>';
$( ".sub-menu li:first-child" ).before(open1col);
$( ".sub-menu li:nth-child(3)" ).before(close1col);
$( "sub-menu li:last-child" ).after(close2col);
});
but it immediately closed the div after the openning and the 3 <li>
items fell outside.
How can I add only the opening and the closing tags as html strings?
CodePudding user response:
While jQuery takes strings as input, it operates on a DOM.
There are no start tags or end tags, only elements, text nodes, and other nodes.
So, you can't do that.
Work with the DOM instead of trying to fight it.
If you want to create a div and then move some elements inside it, do that.
const col = jQuery('<div />');
col.append($( ".sub-menu li:first-child"));
etc.
CodePudding user response:
That's not how DOM works. You can't insert opening and closing tags separately.
For wrapping elements you can use the jQuery .wrapAll
method which wraps all the selected elements with a wrapper element.
let wrapper = '<div ></div>'
$('.sub-menu li').slice(0, 3).wrapAll(wrapper).end().slice(3).wrapAll(wrapper);
Note that the result you are looking for produces invalid HTML. ul
element should only have li
, script
or template
children.