A
A
Artyom Innokentiev2015-11-10 13:01:16
JavaScript
Artyom Innokentiev, 2015-11-10 13:01:16

How to get text from container but not include children?

Markup like this:

<p>
    <s>2</s>
    1
</p>


It is necessary to pull out 1 - what ways through jQuery, JavaScript?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2015-11-10
@artinnok

On pure js:

var p = document.getElementsByTagName('p')[0],
    text = '',
    child,
    index;

for (index = 0; index < p.childNodes.length; index++) {
    child = p.childNodes[index];
    
    if (child.nodeType == Node.TEXT_NODE)
    {     
        text += child.nodeValue;
    }
}

console.log(text);

If necessary, add an empty node check to your liking. In the above code, there are two text nodes, for example, one of which consists only of a carriage return.
UPD : In fact, you can not check for emptiness and use the trim () method. If you need IE8- support, there is a . It all depends on the specific task and markup.
UPD2 : Of course, the jQuery code is 100500 times slower , but the real performance difference will only be noticeable on gigantic volumes or very, very, very slow machines, so if the project is already using jQuery, it makes sense to use the option that Denis suggested , like the most readable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question