简体   繁体   English

javascript:检查标记是否彼此相邻

[英]javascript: Checking if tags are next to each other

So here is the problem: I want to check if element <x-statement> is right next to <p> and there is no text in between them. 所以这是问题所在:我想检查元素<x-statement>是否在<p>旁边,并且它们之间没有文本。 So this will return true: 因此,这将返回true:

<div>
     <x-statement>[discover.prev]</x-statement>
     <p>Go forward<p>
</div>

But this won't: 但这不会:

<div>
     <x-statement>[discover.prev]</x-statement>
     im in the way herr der
     <p>Go forward<p>
</div>

This what I've tried to do: 这是我尝试做的:

if($(this).next().is('p')){
    alert("p is next to you");
}
<div id="div1">
     <x-statement>[discover.prev]</x-statement>
     <p>Go forward<p>
</div>

<div id="div2">
     <x-statement>[discover.prev]</x-statement>
     im in the way herr der
     <p>Go forward<p>
</div>

var exp = /<x-statement>.*<\/x-statement>\s*\n*<p>.*<\/p>/;
alert(exp.test($("#div1").html()));
alert(exp.test($("#div2").html()));

Example on JSFiddle: http://jsfiddle.net/PL9pN/ JSFiddle上的示例: http : //jsfiddle.net/PL9pN/

Here's a more robust function using DOM methods 这是使用DOM方法的更强大的功能

function nextIs(self, tag) {
    return self ? ((function(el) {
        while(el && el.nodeValue && el.nodeValue.trim() == '' ) el = el.nextSibling
        return el;
    })(self.nextSibling).tagName || '').toLowerCase() === tag : false;
}

can be used as 可以用作

var element = document.querySelector('x-statement');
var isNextP = nextIs(, 'p');

FIDDLE 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM