Skip to content

SetAttribute on a specific position in Javascript

I have the following iframe

<iframe frameborder="0" src="//" class="note-video-clip"></iframe>

When I target iframe through getElementsByTagName like this

let a = document.getElementsByTagName("iframe")[0];
a.setAttribute('allowfullscreen', '');

It returns:

<iframe frameborder="0" src="//" class="note-video-clip" allowfullscreen=""></iframe>

It’s creating a problem for me because it is not working as expected. When I manually insert allowfullscreen at beginning it’s working well.

This is the result I want instead

<iframe allowfullscreen="" frameborder="0" src="//" class="note-video-clip" ></iframe>

What am I doing wrong?



One simple way to add allowfullscreen="" just after the tag name is to modify the outerHTML of the element using string method split and array method splice as in the code below.

const miFrame = document.getElementsByTagName("iframe")[0];

// Split the outerHTML string into separate pieces
// by using a space as the separator
const miFrameOH = miFrame.outerHTML.split(' ');

// Using splice(position, deleteCount, itemToAdd),
// add attribute at index 1
miFrameOH.splice(1, 0, 'allowfullscreen=""');

// Join the parts (including the attribute) with a space separator and
// set this string to the outerHTML
miFrame.outerHTML = miFrameOH.join(' ');
<iframe frameborder="0" src="//" class="note-video-clip"></iframe>
User contributions licensed under: CC BY-SA
9 People found this is helpful