简体   繁体   English

如何从元素子元素获取文本?

[英]how to get text from element children?

I have a div element with some span children.我有一个带有一些 span 子元素的 div 元素。 I want to get the text of all spans with space between them and compare that text with a string.我想获取所有跨度的文本,它们之间有空格,并将该文本与字符串进行比较。 my code is here:我的代码在这里:

 var text = "this is some text in div"; var div = document.getElementById("div"); var btn = document.getElementById("btn"); btn.addEventListener("click", function() { var divtext = ""; for (i = 0; i < div.children.length; i++) { divtext += div.children[i].innerHTML + " "; } console.log(divtext.localeCompare(text)) })
 <div id="div"><span>this</span><span>is</span><span>some</span><span>text</span><span>in</span><span>div</span></div> <button id="btn">click</button>

when I use localeCompare for string and div inner text the result should be 0 but it is not.当我对字符串和 div 内部文本使用localeCompare ,结果应该是 0 但它不是。 where is the problem?问题出在哪儿?

Your comparison isn't equal ( 0 ), because there is a trailing space at the end of divtext .您的比较不相等 ( 0 ),因为divtext末尾有一个尾随空格。

If you assign the text from each <span> to an array, you can use the Array.prototype.join method to concatenate the values with a ' ' separator, thus eliminating the trailing space.如果您将每个<span>的文本分配给一个数组,则可以使用Array.prototype.join方法将值与' '分隔符连接起来,从而消除尾随空格。

 var text = "this is some text in div"; var div = document.getElementById("div"); var btn = document.getElementById("btn"); btn.addEventListener("click", function() { var divtext = []; for (i = 0; i < div.children.length; i++) { divtext.push(div.children[i].innerHTML); } console.log(text.localeCompare(divtext.join(' '))); })
 <div id="div"><span>this</span><span>is</span><span>some</span><span>text</span><span>in</span><span>div</span></div> <button id="btn">click</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM