Split the string based on
tag using jquery

前端 未结 10 848
温柔的废话
温柔的废话 2021-01-17 20:04

How can i split the string containing
tag using jquery. I tried the following code but it get error in console. I am not sure how to split the strin

10条回答
  •  悲&欢浪女
    2021-01-17 21:01

    That's no jQuery solution, but hopefully somebody will find it useful. The function returns one or two elements.

    function splitContentsOnBr(el) {
        const before = document.createElement('div');
        const after = document.createElement('div');
        let found = false;
        el.childNodes.forEach(c => {
            if (found) {
                after.appendChild(c.cloneNode(true));
            } else if (c.tagName == 'BR') {
                found = true;
            } else {
                before.appendChild(c.cloneNode(true));
            }
        });
        return after.childNodes.length ? [before, after] : [before];
    }
    document.querySelector('#result').innerHTML = splitContentsOnBr(document.querySelector('h1'))
        .map(el => el.textContent.trim())
        .join(', ');

    First part
    Second part

提交回复
热议问题