javascript - jquery select text - Stack Overflow

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

<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
<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
Share Improve this question edited Apr 7, 2009 at 23:15 ChadT 7,7232 gold badges43 silver badges59 bronze badges asked Apr 7, 2009 at 22:54 csscss
Add a ment  | 

3 Answers 3

Reset to default 5
$("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
});

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)

Plain JS version:

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745131871a4613010.html

相关推荐

  • javascript - jquery select text - Stack Overflow

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

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信