I need to update the following HTML to wrap each <li>
with <li><li-text>{li value}</li-text>
<ul><li>one</li><li>two<ul><li>three<ul><li>four<ul><li>five</li></ul></li></ul></li></ul></li></ul>
hints: I ONLY USING JS, NO JQUERY
I’m trying this, but it’s not working as expected!
var html = `<ul><li>one</li><li>two<ul><li>three<ul><li>four<ul><li>five</li></ul></li></ul></li></ul></li></ul>`.replace(/<li[^>]*>/g,'<li><li-text>$&</li-text>')
The result I’m getting is not correct! the value of list should be between <li-text></li-text>
tags!
<ul><li><li-text><li></li-text>one</li><li><li-text><li></li-text>two<ul><li><li-text><li></li-text>three<ul><li><li-text><li></li-text>four<ul><li><li-text><li></li-text>five</li></ul></li></ul></li></ul></li></ul>
2
Answers
Forget about parsing HTML yourself. You can use the browser’s built-in parser, select your
li
elements, and replace the content to be wrapped withli-text
.Parse the content as HTML, select all
<li>
elements, then replace each direct-children text node with a wrapper:Try it: