i have a question, can i replace html tag to another ?
But i don\'t want to make the content blank. like this:
content<
sure, but why?
var a = document.getElementsByTagName('a');
var src, el, attrs;
for(var i=0,l=a.length;i<l;i++) {
src = a[i];
el = document.createElement('div');
attrs = src.attributes;
for(var j=0,k=attrs.length;j<k;j++) {
el.setAttribute(attrs[j].name, attrs[j].value);
}
el.innerHTML = src.innerHTML;
src.parentNode.replaceChild(el, src);
}
Here's a simple way to do it in your HTML code. With a bit of embedded styling and javascript code, this gives you the effect you're looking for...
<div style="display: inline; color: blue;" onclick="window.location='link/url';">Click!</div>
<input id="tmpType" type="text" name="password" />
<script type="text/javascript">
document.getElementById('tmpType').type = 'password';
</script>
I used this to show/hide password on my dynamic form
Here's a way to change the tag of an element with no jQuery -
// Just provide the element and the new tag
function changeTag(el, newTag) {
var outerHTML = el.outerHTML // Get the outerHTML of the element
var tag = el.tagName // Get the tag of the outerHTML
var r = new RegExp(tag, 'i') // Prepare a RegExp to replace the old tag with the new tag
outerHTML = outerHTML.replace(r, newTag) // Replace it
el.outerHTML = outerHTML // Set the outerHTML of the element
}
<span>Span 1</span> -- <span>Span 2</span>
<br>
<button onclick="changeTag(document.querySelector('span'), 'div')">
Change tag
</button>
It would be invalid HTML (div
elements do not have a href
attribute) and not act like a link anymore.
However, you could emulate the behaviour using JavaScript:
$('div').on('click', function() {
location.href = $(this).attr('href');
});
But please do not do this. It breaks middle-mouse-clicks (for a new tab) for example.
No. You cannot change the tagName (nodeName) of a DOM node.
You only could create a new node of the wanted type, copy all attributes (and maybe properties) and move the child nodes. Yet you would loose inaccessible things like attached event listeners. This technique is for example used when you want to change the type of an input in IE.
However, there is absolutely no reason to change an a
into a div
, they have completely different semantics (also behaviour and layout).