Getting the contents of an element WITHOUT its children

前端 未结 5 1456
醉话见心
醉话见心 2020-12-10 11:18

I have a mild preference in solving this in pure JS, but if the jQuery version is simpler, then jQuery is fine too. Effectively the situation is like this

&l         


        
5条回答
  •  借酒劲吻你
    2020-12-10 11:58

    With js only:

    Try it out: http://jsfiddle.net/g4tRn/

    var result = document.getElementById('thisone').firstChild.nodeValue;    
    
    ​alert(result);​
    

    With jQuery:

    Try it out: http://jsfiddle.net/g4tRn/1

    var result = $('#thisone').contents().first().text();  
    
    alert(result);​
    

    Bonus:

    If there are other text nodes in the outer that you want to get, you could do something like this:

    Try it out: http://jsfiddle.net/g4tRn/4

    var nodes = document.getElementById('thisone').childNodes;
    var result = '';
    
    for(var i = 0; i < nodes.length; i++) {
        if(nodes[i].nodeType == 3) {       // If it is a text node,
            result += nodes[i].nodeValue;  //    add its text to the result
        }
    }
    
    alert(result);
    ​
    

提交回复
热议问题