lee lee - 6 months ago 50
Javascript Question

replace all specific character inside div with jquery

I'm trying to replace all the commas (",") inside the div with a character. I've tried googling and it seems .replace() replaces only the first comma and it removes the links from the

text1
.

How do I replace all the commas with another character inside the div without it removing the links, using jquery?

<div>
<a href="#">text1</a>, <a href="#">text2</a>, <a href="#">text3</a>, <a href="#">text4</a>,
</div>

Answer

Get all text node inside the div and update it, that will be the better way than updating entire html inside div.

$('div')
  .contents() // get all child nodes
  .each(function() { // iterate over them
    if (this.nodeType == 3) // check node type is text
      this.textContent = this.textContent.replace(/,/g, '+'); // update text content if it's text node
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <a href="#">text1</a>, <a href="#">text2</a>, <a href="#">text3</a>,
</div>