Replace multiple
's with only one

前端 未结 9 2279
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-01 12:55

How do I use JavaScript to detect




to become one


?

I trie

9条回答
  •  不要未来只要你来
    2021-02-01 13:11

    CSS Solution

    If you want to disable the effect of multiple
    on the page, you can do it by CSS without using JavaScript:

    br + br { display: none; }
    
    • Check the jsFiddle demo.

    However, this method is ideal when you are working with tags, something like this:

    Text



    Text



    Text



    In other cases, like this:

    Hello World

    Hello World

    Hello World

    It will fail (as CSS passes text nodes). Instead, use a JavaScript solution.


    JavaScript Solution

    // It's better to wait for document ready instead of window.onload().
    window.onload = function () {
        // Get all `br` tags, defined needed variables
        var br = document.getElementsByTagName('br'),
            l = br.length,
            i = 0,
            nextelem, elemname, include;
            
        // Loop through tags
        for (i; i < l - 1; i++) {
            // This flag indentify we should hide the next element or not
            include = false;
            
            // Getting next element
            nextelem = br[i].nextSibling;
            
            // Getting element name
            elemname = nextelem.nodeName.toLowerCase();
            
            // If element name is `br`, set the flag as true.
            if (elemname == 'br') {
                include = true;
            }
            
            // If element name is `#text`, we face text node
            else if (elemname == '#text') {
                // If text node is only white space, we must pass it.
                // This is because of something like this: `

    ` if (! nextelem.data.replace(/\s+/g, '').length) { nextelem = br[i+1]; include = true; } } // If the element is flagged as true, hide it if (include) { nextelem.style.display = 'none'; } } };
    • Check the jsFiddle demo.

提交回复
热议问题