香草Javascript相当于jQuery not()

这就是我在jQuery中所做的:

var text2 = $(node).not("span").text(); console.log(text2); 

我如何在纯JavaScript中做同样的事情?

我知道如何在javascript中获取元素,但不知道如何忽略元素并选择其余元素

 var spans = node.getElementsByTagName('span'); 

我需要获取node中不包含每个元素

这是我的HTML

    Farley 
Sex: Male
DOB: 12/08/2010
Weight: 20 lbs
Location: Kennel 2B
Temperament: Aggresive
Allergies: Sulfa, Penicillin, Peanuts
Cunningham, Stephanie Dog Pomeranian PQRST1234567

或者在此页面的控制台中运行的快速示例:

 var startNode = jQuery("li.related-site").get(0); // quick jQ to get a testable node. var spanLess = []; var child = startNode.firstChild; while(child){ if(child.nodeType == 1){ var anySpans = child.getElementsByTagName('span'); if(!anySpans.length) spanLess.push(child); } child = child.nextSibling; } spanLess; 

根据您的注释,您尝试提取与tablesorter一起使用的值,您可能会发现有用的function是从节点中提取文本值而不管标记:

 function extractText(node){ if(node.nodeType == 3) return node.nodeValue.trim(); if(node.nodeType == 1){ var buf = []; var child = node.firstChild; while(child){ var val = extractText(child); if(val) buf.push(val); child = child.nextSibling; } return buf.join(' '); } return ''; } 

尝试querySelectorAll

  var notSpans = document.getElementsByTagName('div')[0].querySelectorAll(':not(span)'); for (var i = 0; i < notSpans.length; i++) { notSpans[i].style.color = 'green'; } 
 

not a span

a span

感谢bknights,我能够根据自己的需要修改他的答案。

我的全部function如下:

  var myTextExtraction = function (node) { //console.log(node); var child = node.firstChild; while (child) { if (node.getElementsByTagName('span').length) { childValue = child.nextSibling.innerHTML; console.log(childValue); } else { childValue = child.nodeValue console.log(childValue); } return childValue; } } 

然后我用tablesorter插件创建node对象:

 // Load the table sorter $(".table").tablesorter( { textExtraction: myTextExtraction } ); 

这将循环并输出

mytext

的文本以及

myothertext

的文本。 我在jquery TableSorter插件中使用它来处理

的复杂数据