Jquery select text

<div>select this<strong>dfdfdf</strong></div>
<div><span>something</span>select this<strong>dfdfdf</strong></div>

how can i use jquery or just javascript to select div tag value but not include child elements

//output
select this
+3
source share
3 answers
$("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
});
+5
source

Using XPath, you can select only text node children of the div. Raw javascript below.

var xpr = document.evaluate("//div/text()",document,null,
    XPathResult.STRING_TYPE,
    null);
console.log(xpr.stringValue);

> select this


If you have text alternating with tags:

<div>select this<strong>dfdfdf</strong>and this</div>

... you can iterate over them (helper converts XPathResult to an array)

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

(tested in FF, w / firebug logging)

+1
source

Normal version of JS:

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('');
}
+1
source

Source: https://habr.com/ru/post/1706081/


All Articles