Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

Most web browsers completely ignore comments. Instead, try to do something like this

Even if it's possible to read comments on a page, I believe any of the following approaches would be better because comments should be separate from code.

<pre class="language">

or

<pre data-language="language">

So then you can access it with

$(".language")

or

$("pre[data-language=language]")
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top