2

Let's say I have a DIV as below.

<div id="mydiv">
    <p class="abc">some text here</p>
    <p class="xyz"><img src="img.jpg" title="my img"/> some "double quoted text" here</p>
</div>

I read the inner html of the div.

var originalcontent = $("mydiv").html();

Now I need to replace double quotes for the texts only but not for the tag attributes. So my output should be as below.

var myoutput = '<p class="abc">some text here</p><p class="xyz"><img src="img.jpg" title="my img"/> some &quot;double quoted text&quot; here</p>'

Can you suggest me a solution please. Thank you!

asankasri
  • 476
  • 1
  • 6
  • 18
  • Keep using the DOM. Grab the `children` then do what you need to do with the `textContent`. – elclanrs Dec 26 '13 at 04:27
  • possible duplicate of [How do I select text nodes with jQuery?](http://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery) – Barmar Dec 26 '13 at 04:28

2 Answers2

3

Try this:

function replace_text(node){ 
  node = node || document.getElementById('mydiv'); // Change 'mydiv' if you need 

  var children = node.childNodes;
  var i = 0;

  while(node = children[i]){ // While-loop

    if (node.nodeType == 3){ // Some text, replace
        if (node.textContent) { // Not IE (IE's equivalent to textContent is nodeValue)
            node.textContent = node.textContent.replace(/"/g, '&quot;');
        }
        else { // IE
            node.nodeValue = node.nodeValue.replace(/"/g, '&quot;');
        }
    } else { // not text, take step further
      replace_text(node); 
    } 
    i++; 
  } 

} // While-loop


// Don't forget to call function
replace_text();
display-name-is-missing
  • 4,424
  • 5
  • 28
  • 41
0

With Jquery You can do this :

    String.prototype.replaceAll = function(stringToFind,stringToReplace){
    var temp = this;
    var index = temp.indexOf(stringToFind);
        while(index != -1){
            temp = temp.replace(stringToFind,stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
   };
    $(function(){                     

            $("#mydiv").children().each(function(){
                 var text=$(this).text(); 
                 text=text.replaceAll("\"","&quot;"); 
                 //alert(text);
                 $(this).text(text); 
             });
    });
SeeTheC
  • 1,560
  • 12
  • 14