views:

291

answers:

1

I am using CEWP (webpart) and putting this code in there. But this code is not going inside <head> tag. I need to insert this code in <head> tag,

<script src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt;

<script type="text/javascript">
$("*").each(function () { if ($(this).children().length == 0) { $(this).text($(this).text().replace('Respuesta','Responder')); } });
</script>

How can I do this? How this code will work in CEWP webpart?

+3  A: 

Firstly, you can put the code in the <head> if you set it to run at document ready time.

However, it's still not going to work. You're iterating over all tags. Including <html>, which will be the first one selected by $('*').

So you read all the text inside the <html> element (ie. the entire document text), do a string replace on it, then write it back to the html text(). Replacing all the previous text and element content of the <html> element with a single simple text string. And thereby destroying every other element on the page. Oops.

What you want to do is find every text node and do a separate string replace on it:

$(document).ready(function() {
    $('*').each(function() {
        for (var i= this.childNodes.length; i-->0;) {
            var child= this.childNodes[i];
            if (child.nodeType===3) // TEXT_NODE
                child.data= child.data.replace(/Respuesta/g, 'Responder');
        }
    });
});

(Note there are still a bunch of possible edge cases here with form fields and other elements where changing the text inside them might not do what you expect.)

bobince
You can put that javascript wherever you want, but don't forget to _spBodyOnLoadFunctionNames.push("myFunction")
Janis Veinbergs