d24
d24

Reputation: 97

Replace content of span with JS

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

Answers (4)

Mustafa Guner
Mustafa Guner

Reputation: 71

In order to replace particular whitespaces in the strings, you can use REGEX as well.

 y.textContent.replace(/\s/g,'');

Upvotes: 0

i eat bananas
i eat bananas

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

Mamun
Mamun

Reputation: 68933

Two issues in your code:

  1. You are using the element itself not the text content, you have to use the text using innerText or textContent.
  2. The 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

Bastian Fie&#223;inger
Bastian Fie&#223;inger

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

Related Questions