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="">Diablo</a>

Is this possible?

Answers 1

  • 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

Related Articles