I have the following iframe
JavaScript
x
2
1
<iframe frameborder="0" src="//www.youtube.com/embed/adLvq2haaFg" class="note-video-clip"></iframe>
2
When I target iframe
through getElementsByTagName
like this
JavaScript
1
3
1
let a = document.getElementsByTagName("iframe")[0];
2
a.setAttribute('allowfullscreen', '');
3
It returns:
JavaScript
1
2
1
<iframe frameborder="0" src="//www.youtube.com/embed/adLvq2haaFg" class="note-video-clip" allowfullscreen=""></iframe>
2
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
JavaScript
1
2
1
<iframe allowfullscreen="" frameborder="0" src="//www.youtube.com/embed/adLvq2haaFg" class="note-video-clip" ></iframe>
2
What am I doing wrong?
Advertisement
Answer
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.
JavaScript
1
15
15
1
const miFrame = document.getElementsByTagName("iframe")[0];
2
console.log(miFrame);
3
4
// Split the outerHTML string into separate pieces
5
// by using a space as the separator
6
const miFrameOH = miFrame.outerHTML.split(' ');
7
8
// Using splice(position, deleteCount, itemToAdd),
9
// add attribute at index 1
10
miFrameOH.splice(1, 0, 'allowfullscreen=""');
11
12
// Join the parts (including the attribute) with a space separator and
13
// set this string to the outerHTML
14
miFrame.outerHTML = miFrameOH.join(' ');
15
console.log(document.getElementsByTagName("iframe")[0].outerHTML);
JavaScript
1
1
1
<iframe frameborder="0" src="//www.youtube.com/embed/adLvq2haaFg" class="note-video-clip"></iframe>