1

How can I turn a DIV into an input button?

This works great for a checkbox to turn it into a type text:

$('#mycheckbox').get(0).type = 'text';

But that doesn't work, nothing happens:

$('#mydiv').get(0).type = 'button'; //formatting
Sanjit Bhardwaj
  • 863
  • 6
  • 13
smolo
  • 280
  • 4
  • 18

4 Answers4

1

You can use replaceWith for div.

$("#mydiv").replaceWith("<input type='button' value='MyButton'>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='mydiv'></div>
Shree
  • 18,997
  • 28
  • 86
  • 133
  • Thanks, this works all fine! Now I just need to figure out how to attach an onclick event handler to that button – smolo Feb 02 '19 at 05:30
  • See this old and epic question how dynamic added dom work. https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Shree Feb 02 '19 at 05:32
  • Thanks, works all fine like this: $("#nuBreadcrumb0").replaceWith("") $("#nuBreadcrumb0").click(function(){ alert('click!');}); – smolo Feb 02 '19 at 05:38
0

You cannot change div to button.

You can turn checkbox to text because you change <input type="checkbox"> to <input type="text">. But There's no <div type="button"> in HTML.

NoobTW
  • 2,017
  • 2
  • 19
  • 35
0

you can't change a tagName, but you could change it to a submit

$('#mydiv').get(0).type = 'submit';

better

$('#mydiv').attr('type','submit'); // jQuery
David Bray
  • 566
  • 1
  • 3
  • 14
0

this will loop through all buttons in the page and change it them into div's

    var Btns = document.querySelectorAll('button');
    
    Btns.forEach(changeNodeName)
  
    function changeNodeName(el){
        console.log(el)
        var elNodeName = el.nodeName.toLowerCase();
        var newString = el.outerHTML.trim()
        .replace('<'+ elNodeName,'<div');
    
        // To replace the end tag, we can't simply use replace()
        // which means if our element has a child element with the
        // same node name the end tag of the *child element* will be 
        // replaced, not the parent element. So,
        
        newString = newString
        .slice(0,newString.lastIndexOf('</div>'));    
        //now newString = "<div id='element'>Text" 'without closing tag'
        
        newString = newString + "</div>";
        el.outerHTML = newString;
        
        // because, replace() will replace the first occurrence,
    }
yaakov
  • 1
  • 3