Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery select text

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

how do i use jquery or just javascript to select the value of the div tag but not include any child elements

//output
select this

2 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
});
like image 59
geowa4 Avatar answered Nov 22 '25 15:11

geowa4


Using XPath, you can select only the 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 interspersed with tags:

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

...you can iterate over them (helper converts XPathResult to 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)

like image 40
Chadwick Avatar answered Nov 22 '25 14:11

Chadwick