最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to extract text from div in javascript without extracting from children divs? - Stack Overflow

programmeradmin2浏览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"?

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"?

Share Improve this question asked Jul 19, 2016 at 8:57 quantumbutterflyquantumbutterfly 1,9534 gold badges28 silver badges39 bronze badges 1
  • get the innerhtml , then trim out the <div>....</div> section , just a suggestion – Arun Prasad E S Commented Jul 19, 2016 at 9:02
Add a ment  | 

6 Answers 6

Reset to default 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;
document.getElementsByClassName('targetDiv')[0].childNodes[0].textContent

See below code :

$(document).ready(function(){
  alert($(".targetDiv")
    .clone()
    .children()
    .remove()
    .end()
    .text());
  });
<script src="https://ajax.googleapis./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>

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();

You can replace Target text by

Target text

And call getElementById("MyText") in your code

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

发布评论

评论列表(0)

  1. 暂无评论