How to get only directly contained text in DOM element in Javascript?

.clone() clones the selected element.

.children() selects the children from the cloned element

.remove() removes the previously selected children

.end() selects the selected element again

.text() gets the text from the element without children

const elementText = $("#price").clone()
                                .children()
                                .remove()
                                .end()
                                .text();

console.log(elementText.trim().split("\n")[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent">
  Parent
  <span>Child 1</span>
  <span>Child 2</span>
</div>

<div id="price">
   100$
   <span>some ads</span>
   <span>another ads</span>
   for each
</div>

EDIT: You can also use this:

$("#price").contents().get(0).nodeValue.trim()

Filter the childNodes to include only text nodes and use textContent of each of the matching nodes:

const text = Array.prototype.filter
    .call(element.childNodes, (child) => child.nodeType === Node.TEXT_NODE)
    .map((child) => child.textContent)
    .join('');

The text includes the full markup of the text, including newlines. If this is undesired, use text.trim().

The filter.call is used because childNodes is a NodeList, which is array-like, but does not support .filter method.


To get text only for the first node

const text = Array.prototype.filter
    .call(element.childNodes, (child) => child.nodeType === Node.TEXT_NODE)[0];

Alternatively, if you can rely on the fact that the value is always the first child, the above can be simplified to

const text = element.childNodes[0];