Search code examples
javascriptreplaceuserscripts

Userscript, how to replace HTML tag and attributes


I am trying to change the HTML tag and remove the class/style attributes after the tag. I already know how to do this if I create the code before hand and replace, now I want to know how to find the tags on an already loaded page and replace them with my js.

var s = "<h2 class=\"title\" style=\"font-color: red;\">Blog Post</h2>";
s = s.replace("<h2 class=\"title\" style=\"font-color: red;\">","<p>");
s = s.replace(/<\/h2>/g, "</p>");

Start with <h2 class="title" style="font-color: red;">Blog Post</h2>

End with <p>Blog Post</p>

So the question is how can I create the var s with existing HTML? How do I find h2.title on a page and give it to var s?

edit I have no javascript experience except for this script which I found and tweaked. Please explain how I can grab text from an existing document, and make it my var for s.replace to manipulate.


Solution

  • Don't try to do it with regular expressions, you should use DOM manipulation to move the text node in question to a p tag you create. Here's some code that will do what you need.

    http://jsfiddle.net/jWRh5/

    // Find the h2
    var h2 = document.querySelector("h2");
    // Create the p element you need
    var p = document.createElement("p");
    // Move the text node into the p element
    p.appendChild(h2.firstChild);
    // Insert the p element before the h2
    h2.parentNode.insertBefore(p, h2);
    // Get rid of the h2
    h2.parentNode.removeChild(h2);
    

    If you want to go against what every one else suggests, here's a way to use RegExp to achieve what you need http://jsfiddle.net/jWRh5/1/

    It uses a not well supported feature, outerHTML (it does work in most recent versions of the major browsers)

    var h2 = document.querySelector("h2.title");
    var s = h2.outerHTML;
    s = s.replace("<h2 class=\"title\" style=\"font-color: red;\">","<p>");
    s = s.replace(/<\/h2>/g, "</p>");
    h2.outerHTML = s;
    

    Here's how to do it for all h2.titles on your page (not using the RegExp way since that's a really poor way, but if you're really set on using it, you can use it as a guide)

    var h2s = document.querySelectorAll("h2.title");
    // Loop backwards since we're modifying the list
    for (var i = h2s.length -1 ; i >=0; i--) {
        var h2 = h2s[i];
        var p = document.createElement("p");
        p.appendChild(h2.firstChild);
        h2.parentNode.insertBefore(p, h2);
        h2.parentNode.removeChild(h2);
    }