Search code examples
jqueryuserscriptsreplacewith

How to replace a <button> with <a> and saving all attributes


<div class="pagination">
        <button class="ajax left" data-href="" rel="prev"></button>
        <button class="active">1</button><button class="ajax" data-href="/legenda/carrega_destaques/todos/2">2</button>
        <button class="ajax" data-href="/legenda/carrega_destaques/todos/3">3</button>
        <button class="ajax" data-href="/legenda/carrega_destaques/todos/4">4</button>
        <button class="ajax" data-href="/legenda/carrega_destaques/todos/5">5</button>
        <button class="ajax" data-href="/legenda/carrega_destaques/todos/6">6</button>
        <button class="ajax" data-href="/legenda/carrega_destaques/todos/7">7</button>
        <button class="ajax" data-href="/legenda/carrega_destaques/todos/8">8</button>
        <button class="ajax" data-href="/legenda/carrega_destaques/todos/9">9</button>
        <button class="ajax right" data-href="/legenda/carrega_destaques/todos/2" rel="next"></button>
</div>

I came to this code with some research:

$("button").on('load',function(){
    var buttonclass = $(this).attr('class');
    var buttonrel = $(this).attr('rel');
    var buttondatahref = $(this).attr('data-href');
    var buttonText = $(this).html();
    $(this).replaceWith("<a class=" + buttonclass + " rel=" + buttonrel + " href=" + buttondatahref + ">" + buttonText + "</a>");
            }
});

Im get some error like last button with class "java right" or "java left" save only "java" word and some undefined attribute. And this will become a userscript to greasemonkey in someway. If someone can help or know a simply way to do this will be great.


Solution

  • I found this solution:

    function addEventListener(){
        var replacementTag = 'a';
    // Replace all a tags with the type of replacementTag
    $('div.pagination>button').each(function() {
        var outer = this.outerHTML;
    
        // Replace opening tag
        var regex = new RegExp('<' + this.tagName, 'i');
        var newTag = outer.replace(regex, '<' + replacementTag);
    
        // Replace closing tag
        regex = new RegExp('</' + this.tagName, 'i');
        newTag = newTag.replace(regex, '</' + replacementTag);
    
        $(this).replaceWith(newTag);
    
    });
    }