user3344734 user3344734 - 8 months ago 48
Javascript Question

Change attribute type

Is it possible to change the attribute

type
of an element? Scrathing my head about this - all I can find is how to change the
value
of an attribute.

I want to change
href
to
src
on the element above. I have a script that change the element type to an iframe for mobiles, and I need the attribute to be a src type for it to work.

<a class="colorbox cboxElement" href="http://example.com">Diablo</a>


Is this possible?

Answer Source

Use removeAttr() method to remove an attribute and attr() method to set an attribute.

$('.colorbox').attr('src', function() {
  return $(this).attr('href');
}).removeAttr('href');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="colorbox cboxElement" href="http://example.com">Diablo</a>


With pure Javascript use Element#setAttribute method to set attribute where you can get attribute value using Element#getAttribute method and remove an attribute using Element#removeAttribute method.

var ele = document.querySelector('.colorbox');
ele.setAttribute('src', ele.getAttribute('href'));
ele.removeAttribute('href');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="colorbox cboxElement" href="http://example.com">Diablo</a>

FYI : The jQuery method would work for multiple elements, in Javascript you need to iterate over the element collection to update multiple.

For eg:

// for older browser use [].slice.call(....).forEach
Array.from(document.querySelectorAll('.colorbox')).forEach(function(ele){
 // do the rest here
})