1

Is there any way in CSS or jQuery to select only the plain texts inside of an element?

I have an HTML code like this:

<div class="container">
 "some text 1"
 <div> ... </div>
 <img src="#">
 "some text 2"
 <div> ... </div>
</div>

and want to select only the texts that are directly inside the container element.

I have searched on the internet and found some solutions like using first-child(), nth-child(), last-child() but since the texts are not always in the specific positions; using the *-child() selectors don't solve my problem.

Mohandes
  • 452
  • 3
  • 15

2 Answers2

1

The :nth-child() pseudo-class selector only works with Elements, not with Text Nodes.

In order to do that get the parent node, then get child node collection using childNodes property and finally, you can access TextNode by using index. To remove you can use remove() method or use removeChild() method on parent element.

// get parent elemeent
let cont = document.querySelector('.container');

// get child node collection which is a live collection
let nodeCollection = cont.childNodes;

// get first child
let text1 = nodeCollection[0].textContent;
// get next child(index is 4 since there is an empty text node in between div and img)
let text2 = nodeCollection[4].textContent;

// remove the last element first since nodeCollection is live
// collection removing an element will update the index
nodeCollection[4].remove();
nodeCollection[0].remove();

console.log(text1, text2)
<div class="container">
  "some text 1"
  <div> ... </div>
  <img src="#"> "some text 2"
  <div> ... </div>
</div>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0
<div id="myDiv">
    text 1
    <div>div text</div>
    text 2
    <span>span text</span>
</div>

<script>
    $(document).ready(function() {
        var $myDiv = $('#myDiv');
        var texts = [];
        for(var i = $myDiv[0].childNodes.length - 1; i >= 0; i--) {// Starting from last to first, so we can remove from array without breaking JS
            if($myDiv[0].childNodes[i].nodeType == Node.TEXT_NODE) {// Is text only?
                texts.push($myDiv[0].childNodes[i].nodeValue);// Add this text to array
                $myDiv[0].removeChild($myDiv[0].childNodes[i]);// Remove from HTML
            }
        }
        texts = texts.reverse();
        //texts = ["text 1", "text 2"]
    });
</script>
evilReiko
  • 19,501
  • 24
  • 86
  • 102