user3344734 user3344734 - 1 year ago 74
Javascript Question

Change attribute type

Is it possible to change the attribute

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

I want to change
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="">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');
<script src=""></script>
<a class="colorbox cboxElement" href="">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'));
<script src=""></script>
<a class="colorbox cboxElement" href="">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 []
 // do the rest here
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download