Javascript jquery选择文本
使用XPath,您只能选择下面div.Raw javascript的文本节点子节点Javascript jquery选择文本,javascript,jquery,Javascript,Jquery,使用XPath,您只能选择下面div.Raw javascript的文本节点子节点 $("div").contents().each(function(i) { //the function is applied on the node. //therefore, the `this` keyword is the current node. //check if the current element is a text node, if so do somethin
$("div").contents().each(function(i) {
//the function is applied on the node.
//therefore, the `this` keyword is the current node.
//check if the current element is a text node, if so do something with it
});
如果文本中穿插有标记:
var xpr = document.evaluate("//div/text()",document,null,
XPathResult.STRING_TYPE,
null);
console.log(xpr.stringValue);
> select this
(在FF中测试,带有firebug日志)普通JS版本:
function $x(path, context, type) {
if (!context) context = document;
type = type || XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE;
var i,item,arr=[], xpr = document.evaluate(path, context, null, type, null);
for (i=0; item=xpr.snapshotItem(i); i++)
arr.push(item);
return arr;
}
var nodes = $x("//div/text()");
nodes.forEach(function(item) {
console.log(item.textContent);
});
> select this
> and this
函数getDirectTextContent(元素){
var text=[];
对于(var i=0;其函数参数为(i,node),测试在node.nodeName:$(“div”).contents()上。每个(函数(i,node){if(node.nodeName==“#text”)console.log(node.textContent);});该函数应用于节点。因此,
this
关键字是当前节点。
var xpr = document.evaluate("//div/text()",document,null,
XPathResult.STRING_TYPE,
null);
console.log(xpr.stringValue);
> select this
<div>select this<strong>dfdfdf</strong>and this</div>
function $x(path, context, type) {
if (!context) context = document;
type = type || XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE;
var i,item,arr=[], xpr = document.evaluate(path, context, null, type, null);
for (i=0; item=xpr.snapshotItem(i); i++)
arr.push(item);
return arr;
}
var nodes = $x("//div/text()");
nodes.forEach(function(item) {
console.log(item.textContent);
});
> select this
> and this
function getDirectTextContent(element) {
var text= [];
for (var i= 0; i<element.childNodes.length; i++) {
var child= element.childNodes[i];
if (child.nodeType==3) // Node.TEXT_NODE
text.push(child.data);
}
return text.join('');
}