Search code examples
javascriptjquerygoogle-code-prettify

jQuery: find comments before pre tag


I try to implement like SO code highlight with pretty-print. How to get comment before pre tag?

<!-- language: some -->
<pre>
...

How to get comment before pre tag?


Solution

  • It requires you to loop through the nodes and check the nodeType and read its nodeValue. An element is a nodeType of 1 and a comment is a nodeType of 8.

    HTML:

    <p>Apple</p>
    <!-- language: some -->
    <pre id="one">One</pre>
    
    
    <!-- language: someOther -->
    <pre id="two">two</pre>
    
    
    <pre id="three">three</pre>
    

    JavaScript:

    var pres = $("pre");
    pres.each(
        function() {
            var prevSibling = this.previousSibling;
            var nodeValue = null;
            while (prevSibling && prevSibling.nodeType!==1) {
                if (prevSibling.nodeType === 8) {
                    nodeValue = prevSibling.nodeValue;   
                }
                prevSibling = prevSibling.previousSibling;
            }        
            console.log(this.innerHTML, nodeValue);
        }
    );
    

    Example:

    JSFiddle