Question

i do not know much about javascript searched long, but didn't get the reslut i need.

i want to replace on page load this

<p>---SOMERANDOMTEXT:::</p>

with

<strong>SOMERANDOMTEXT</strong>

played with this an many other snippets..

<script type="text/javascript">
    window.onload = function() {
        function myscript() {
            input = '---';
            output='New Text';
            document.body.innerHTML = document.body.innerHTML.replace(input,output);
        }
    }
</script>
Was it helpful?

Solution

Here is the fast and fool proof way of replacing <p> tags with <strong> tags:

var ps = document.getElementsByTagName('p');
for (var i = ps.length; i--;) {
    var strong = document.createElement('strong'),
        p = ps[i];

    while (p.firstChild) {
        strong.appendChild(p.firstChild);
    }

    p.parentNode.insertBefore(strong, p);
    p.parentNode.removeChild(p);
}

If you need to change the text accordingly, place something like that in the while loop:

if (p.firstChild.nodeType === 3) {
    p.firstChild.nodeValue = p.firstChild.nodeValue.replace(/[-:]{3}/g, '');
}

DEMO: http://jsfiddle.net/5m9Qm/1/

OTHER TIPS

You need to call your myscript function like this -

window.onload = function() {
  myscript();
}
function myscript() {
    var input = '---';
    var output='New Text';
    document.body.innerHTML = document.body.innerHTML.replace(input,output);
}

You are declaring a function myscript but never invoking it. Try this (untested) code:

<script>
window.onload = function(){
    var p = document.querySelector('p');
    var strong = document.createElement('strong');
    strong.innerHTML = 'replaced';
    p.parentNode.replaceChild(strong,p);

})
</script>

Note this requires modern browsers.

You can use a regex.

Try:

output = document.body.innerText.replace(/[-:]{3}/g, '');
document.body.innerHTML = document.body.innerHTML.replace(/<p>---.*:::<\/p>/, '<strong>' + output + '</strong>');

DEMO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top