Reputation: 97
I have multiple span elements:
<span class="sac-chat-name">username : </span>
I want to remove the first space before the colon.
I tried it with JS like this:
var y = document.getElementsByClassName("sac-chat-name");
var i;
for (i = 0; i < y.length; i++) {
y[i].replace(" : ", ": ");
}
but this doesn't work:
Uncaught TypeError: y[i].replace is not a function …
Where is the error?
Upvotes: 0
Views: 2003
Reputation: 71
In order to replace particular whitespaces in the strings, you can use REGEX as well.
y.textContent.replace(/\s/g,'');
Upvotes: 0
Reputation: 76
Mamun said right, you can also go threw an Array, forEach loop is easier to read
var spans = Array.from(document.getElementsByClassName('sac-chat-name'));
spans.forEach(span => {
span.innerHTML = span.innerHTML.replace(" :", ":");
});
Upvotes: 1
Reputation: 68933
Two issues in your code:
innerText
or textContent
.replace()
method returns a new string with some or all matches of a pattern replaced by a replacement. You have to reassign the elements text content by the retuned result of replace()
:var y = document.getElementsByClassName("sac-chat-name");
var i;
for (i = 0; i < y.length; i++) {
y[i].textContent = y[i].textContent.replace(" : ", ": ");
}
<span class="sac-chat-name">username : </span>
Upvotes: 1
Reputation: 335
the JavaScript replace method is a string prototype. With that being said you cannot use it on nodes.
var y = document.getElementsByClassName("sac-chat-name");
var i;
for (i = 0; i < y.length; i++) {
// get the current content
var curText = y[i].innerHTML;
// sanitize content
var sanitized = curText.replace(" : ", ": ");
// replace content
y[i].innerHTML = sanitized;
}
So first of all you have to get the current Content of your element. You can do this using innerHTML
after that you can sanitize the string and replace the HTML of your element.
Upvotes: 1