javascript - Change a dom using .replaceWith -
i have code want. changes strong tags styled h3 tags, perfect, life of me can't figure out replace ".click" make run automatically. tried ".ready" , gives me error in jquery.
$(document).ready(function(){ $('strong').click(function(){ $(this).replacewith($('<h3 style="margin:0px;display:inline;">' + this.innerhtml + '</h3>')) }) });
i'd suggest going straight replacewith():
// (if not all) jquery methods iterate on // collection they're chained: $('strong').replacewith(function () { // here 'this' individual <strong> element on // method iterates, , return created element: return $('<h3 style="margin:0px;display:inline;">' + this.innerhtml + '</h3>'); }); $('strong').replacewith(function () { return $('<h3 style="margin:0px;display:inline;">' + this.innerhtml + '</h3>'); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <strong>1</strong> <strong>2</strong> <strong>3</strong> <strong>4</strong> incidentally, in plain javascript, quite possible:
// creating <h2> element: var heading = document.createelement('h2'), // initialising empty variable: clone; // setting display , margin properties: heading.style.display = 'inline'; heading.style.margin = '0'; // using function.prototype.call() use // array.prototype.foreach() on array-like // nodelist returned document.queryselector(): array.prototype.foreach.call(document.queryselectorall('strong'), function(bold) { // cloning created <h2> element: clone = heading.clonenode(); // setting innerhtml: clone.innerhtml = bold.innerhtml; // traversing parentnode, , // using node.replacechild() replace // existing <strong> element // cloned <h2> element: bold.parentnode.replacechild(clone, bold); }); var heading = document.createelement('h2'), clone; heading.style.display = 'inline'; heading.style.margin = '0'; array.prototype.foreach.call(document.queryselectorall('strong'), function(bold) { clone = heading.clonenode(); clone.innerhtml = bold.innerhtml; bold.parentnode.replacechild(clone, bold); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <strong>1</strong> <strong>2</strong> <strong>3</strong> <strong>4</strong> references:
- javascript:
- jquery:
Comments
Post a Comment