2016-03-07 146 views
2

如果给定元素只有一个子元素(包括文本节点,但忽略空格),如何使用jQuery或JavaScript进行测试。检查元素是否只有一个子元素

示例:对于标记元素“DIV”以下时,测试将失败,因为它有两个子元素:p和文本节点:

<div> 
    <p>Test-1</p> - subline 
</div> 

示例:对于以下标记元素“DIV”,测试应该通过,因为它只有一个子元素:p(尽管空格被忽略):

<div> 
    <p>Test-1</p> 
</div> 

好像element.children()将无法工作,因为它忽略了文本节点。 element.contents()可能有效,但不会忽略空格。

回答

3

你将不得不使用自定义过滤器

var elements = $('div'); 
 

 
elements.each(function() { 
 
    var element = $(this); 
 
    var count = element.contents().filter(function() { 
 
    return this.nodeType == Node.ELEMENT_NODE || (this.nodeType == Node.TEXT_NODE && !!$.trim(this.nodeValue)) 
 
    }).length; 
 

 
    snippet.log(this.id + ': ' + count) 
 
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="1"> 
 
    <p>Test-1</p> 
 
</div> 
 
<div id="2"> 
 
    <p>Test-1</p>1 
 
</div> 
 
<div id="3"> 
 
    <p>Test-1</p><span>x</span> 
 
</div> 
 
<div id="4"> 
 
    2 
 
    <p>Test-1</p>3 
 
</div>

+0

任何方式重构并使其更小。 – Nick

+1

@尼克为什么会这么重要?如果您需要反复使用它,请将其解压缩到一个函数中。 –

+0

@RoryMcCrossan它的工作原理,但简洁一些将是可取的。我尝试重构它:element.contents()。filter(':only-child')。length。如果没有比Arun的答案更好或更短的方法,那么我会很乐意接受它。 – Nick

1

你可以尝试简单的JS作为

element[0].childNodes.length 

这将包括文本节点以及正常的子节点。

如果一个给定的元素只有一个子元素(包括文本节点, 但忽略空格)。

要排除的空格

element.contents().filter(function() { 
    return this.nodeType === 3 && this.nodeValue.trim().length > 0; 
}).length; //to get the number of text nodes which are not white-spaces 

或纯JS

element[0].childNodes.filter(function() { 
    return this.nodeType === 3 && this.nodeValue.trim().length > 0; 
}).length; 
+2

将不排除空格 –

+0

@ArunPJohny所做的更改,但你已经做到了我想 – gurvinder372

0

非jQuery版本。

可以优化,但这个工作。 value.nodeType === 1来检查它是否是一个元素,我们增加计数器。

var count = 0; 
Array.prototype.slice.call(document.getElementById('parent_id_here').childNodes, 0).forEach(function (value) { 
    if (value.nodeType === 1) { 
     count++; 
    } 
}); 

Demo

0

您可以使用此条件:

$('div').html().trim() == $('div > *:first-child')[0].outerHTML.trim() 
相关问题