选择相邻兄弟节点而不插入文本节点 [英] Selecting Adjacent Sibling without intervening text nodes
问题描述
由于悲惨的情况,我收到这样的HTML:
Due to a sad situation I receive HTML like this:
<p>Perform the following commands:
<code>> cd /foo</code><code>> adb shell</code><code># ps</code>
</p>
我需要像下面这样制作代码:
and I need to make code like appear visually like:
Perform the following commands:
> cd /foo
> adb shell
# ps
我以为我会很棘手并使用 CSS相邻兄弟选择器:
I thought I'd be tricky and use the CSS Adjacent Sibling Selector:
code + code:before { content:'\A'; white-space:pre }
...但后来我发现这甚至适用于:
...but then I discovered that this applies even to something like:
<p>If you go to your <code>C:\</code> directory and run <code>dir</code> …</p>
是否只有CSS解决方案来选择相邻元素而不介入非元素节点?
Is there a CSS-only solution to select adjacent elements without intervening non-element nodes?
当且仅当没有时,建议使用JavaScript(包括jQuery)解决方案。
推荐答案
这有效:
$('code').each(function() {
var prev = this.previousSibling;
var next = this.nextSibling;
if ((prev && prev.tagName === 'CODE') ||
(next && next.tagName === 'CODE')) {
$(this).addClass('block');
}
});
然后在你的CSS中使用。阻止
选择器添加 display:block
以及匹配元素的任何其他所需样式。
Then in your CSS use the .block
selector to add display: block
and any other desired styles to the matched elements.
演示在 http://jsfiddle.net/alnitak/JYzGg/
这将是非常好的asy将此代码编写为纯Javascript,如果您还没有加载jQuery - 如果您应该在这些元素上已经有其他类名,则jQuery恰好比纯JS更容易添加类。
It would be pretty easy to code this as pure Javascript if you don't already have jQuery loaded - jQuery just happens to make adding the class easier than pure JS if you should have other class names already on those elements.
这篇关于选择相邻兄弟节点而不插入文本节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!