0

Let's say I have the following html:

<div class="targetDiv">
    Target text
    <div class="junkDiv">
          Text I don't want
    </div

</div>

I know I can find divs like these and extract all of the text recursively by doing document.getElementsByClassName("thread")[x].innerText (where x is the index of the div I want to extract from). This will give me "Target textText I don't want".

My question is how do I extract "Target text" without extracting "text I don't want"?

quantumbutterfly
  • 1,815
  • 4
  • 23
  • 38

6 Answers6

5

Use the childNodes property. In your case, childNodes[0] will contain the text element. Use textContent to get the value of the text element:

document.getElementsByClassName('targetDiv')[0].childNodes[0].textContent;
Tarun Dugar
  • 8,921
  • 8
  • 42
  • 79
3
document.getElementsByClassName('targetDiv')[0].childNodes[0].textContent
zhibirc
  • 180
  • 14
2

See below code :

$(document).ready(function(){
  alert($(".targetDiv")
    .clone()
    .children()
    .remove()
    .end()
    .text());
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="targetDiv">
    Target text
    <div class="junkDiv">
          Text I don't want
    </div>

</div>
Vijay Maheriya
  • 1,617
  • 16
  • 21
0

You can refer this link1, link2

$("#foo")
.clone()    //clone the element
.children() //select all the children
.remove()   //remove all the children
.end()  //again go back to selected element
.text();
Community
  • 1
  • 1
0

You can replace Target text by

Target text

And call getElementById("MyText") in your code

romulus001
  • 318
  • 3
  • 15
0

Try document.getElementsByClassName("targetDiv")[x].textContent

Santanu Dey
  • 2,900
  • 3
  • 24
  • 38