Getting the contents of an element WITHOUT its children

前端 未结 5 1452
醉话见心
醉话见心 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:52

    If you just want the first child then it's rather simple. If you are looking for the first text-only element then this code will need some modification.

    var text = document.getElementById('thisone').firstChild.nodeValue;
    alert(text);
    
    0 讨论(0)
  • 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 <span> 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);
    ​
    
    0 讨论(0)
  • 2020-12-10 12:01

    FROM: http://viralpatel.net/blogs/2011/02/jquery-get-text-element-without-child-element.html

     $("#foo")
            .clone()    //clone the element
            .children() //select all the children
            .remove()   //remove all the children
            .end()  //again go back to selected element
            .text();    //get the text of element
    
    0 讨论(0)
  • 2020-12-10 12:11

    Pure JavaScript

    In this pure JavaScript example, I account for the possibility of multiple text nodes that could be interleaved with other kinds of nodes. Pass a containing NodeList in from calling / client code.

    function getText (nodeList, target)
    {
        var trueTarget = target - 1;
        var length = nodeList.length; // Because you may have many child nodes.
    
        for (var i = 0; i < length; i++) {
            if ((nodeList[i].nodeType === Node.TEXT_NODE) && (i === trueTarget)) {
                return nodeList.childNodes[i].nodeValue;
            }
        }
    
        return null;
    }
    

    You might use this function to create a wrapper function that uses this one to accumulate multiple text values.

    0 讨论(0)
  • 2020-12-10 12:13

    Have you tried something like this?

    var thisone = $("#thisone").clone();
    thisone.children().remove();
    var mytext = thisone.html();
    
    0 讨论(0)
提交回复
热议问题