Search code examples
javascriptelementtagname

Assigning ID to object (just one) with javascript


For some reason, the code below doesn't work. I need it to assign an ID to one object. What am I doing wrong below?

  var frame = document.getElementsByTagName("iframe").setAttribute("id","iframe");

I have a jQuery libary installed, if it should be of any use.


Solution

  • Since you are using jQuery you can make this much simpler:

    $('iframe').attr('id', 'iframe'); // or:
    $('iframe').prop('id', 'iframe');
    

    This affects all <iframe> elements on the page and thus you better have only one. Duplicate IDs are serious business. They break stuff and you really need to avoid them. You could chain in .first() or use the iframe:first selector to make sure you only target the first element.


    Here's the jQuery-less solution, also just for the first <iframe>:

    var frame = document.getElementsByTagName("iframe")[0];
    frame.id = 'iframe';
    

    Line 1: You actually want the (first) iframe element in frame.
    Line 2: The ID is available as a property so you can use .id instead of setAttribute.