Reputation: 15
I have a div element with some span children. 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. where is the problem?
Upvotes: 0
Views: 46
Reputation: 17378
Your comparison isn't equal (0
), because there is a trailing space at the end of 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.
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>
Upvotes: 1