0

Why doesn't this script return the modified element?
The element is indeed changed in the function but not correctly returned.

<script>
x = "<div></div><div></div><div></div><p></p>";
function modify (x) {
    $(x).find('div').each(function(index){
        $(this).html('content text'); 
        $(this).addClass('test') ;
    }); 
    return $(x);
}
modify (x);
</script>
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Alexandru R
  • 8,560
  • 16
  • 64
  • 98
  • That is because when you use `.find()` it will look for child nodes in your element. You will have to wrap your HTML in a wrapper element (like with another `
    `), and unwrap it when you're done before injecting it into the DOM. Might be relevant: http://stackoverflow.com/questions/7159426/using-jquery-to-search-a-string-of-html
    – Terry Jul 28 '15 at 20:06
  • How are you determining if it has changed or not? There is nothing in your code which uses/echoes `x`. – Heretic Monkey Jul 28 '15 at 20:34

1 Answers1

1

The this in your each function is not referring to an element of x. You need to declare an variable to represent the x element this like so -

$(x).find('div').each(function(index, that){
    $(that).html('content text'); 
    $(that).addClass('test') ;
}); 
John C
  • 3,052
  • 3
  • 34
  • 47