Choosing a sibling without intermediate text nodes

Due to the sad situation, I get HTML as follows:

<p>Perform the following commands:
   <code>&gt; cd /foo</code><code>&gt; adb shell</code><code># ps</code>
</p>

and I need to make the code kind of visually like:

Perform the following commands:
> cd /foo
> adb shell
# ps

I thought it would be tricky, and use the Adjacent CSS selector :

code + code:before { content:'\A'; white-space:pre }

... but then I discovered that this even applies to something like:

<p>If you go to your <code>C:\</code> directory and run <code>dir</code></p>

Is there a CSS-only solution for selecting adjacent elements without intermediate non- element nodes ?

If and only if not, feel free to suggest a JavaScript solution (including jQuery).

+3
source share
2 answers

It works:

$('code').each(function() {
    var prev = this.previousSibling;
    var next = this.nextSibling;
    if ((prev && prev.tagName === 'CODE') ||
        (next && next.tagName === 'CODE')) {
        $(this).addClass('block');
    }
});​

Then in your CSS, use the selector .blockto add display: blockany other desired styles for the matched elements.

demo at http://jsfiddle.net/alnitak/JYzGg/

Javascript, jQuery - jQuery , JS, .

+4

, , , :

$('code').each(
    function(){
        if (this.previousSibling == this.previousElementSibling){
            $(this).addClass('block');
        }
        else {
            $(this).addClass('inline');
        }
    });​

JS Fiddle demo.

, , , previousElementSibling ( , , CSS, ).

JavaScript:

var codes = document.getElementsByTagName('code');

for (var i=0, len=codes.length; i<len; i++){
    var cur = codes[i];
    codes[i].className = cur.previousSibling == cur.previousElementSibling ? 'block' : 'inline';
}​

JS Fiddle demo.

( ), :

function addClass(elem,newClass){
    if (!elem) {
        return false;
    }
    else {
        var curClass = elem.className;
        if (curClass.length){
            return curClass + ' ' + newClass;
        }
        else {
            return newClass;
        }
    }
}

var codes = document.getElementsByTagName('code');

for (var i=0, len=codes.length; i<len; i++){
    var cur = codes[i];
    codes[i].className = cur.previousSibling == cur.previousElementSibling ? addClass(cur,'block') : addClass(cur,'inline');
}​

JS Fiddle demo.


, Alnitak ( , , , ):

var codes = document.getElementsByTagName('code');

for (var i=0, len=codes.length; i<len; i++){
    var cur = codes[i];
    codes[i].className = cur.previousSibling == codes[i-1] || cur.nextSibling == codes[i+1]? addClass(cur,'block') : addClass(cur,'inline');
}​

JS Fiddle demo

:

+1

Source: https://habr.com/ru/post/1687375/


All Articles