Javascript 中特定位置的 SetAttribute

SetAttribute on a specific position in Javascript

我有以下iframe

<iframe frameborder="0" src="//www.youtube.com/embed/adLvq2haaFg" class="note-video-clip"></iframe>

当我像这样通过 getElementsByTagName 定位 iframe

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

它returns:

<iframe frameborder="0" src="//www.youtube.com/embed/adLvq2haaFg" class="note-video-clip" allowfullscreen=""></iframe>

这给我带来了麻烦,因为它没有按预期工作。当我在开始时手动插入 allowfullscreen 时,它运行良好。

这是我想要的结果

<iframe allowfullscreen="" frameborder="0" src="//www.youtube.com/embed/adLvq2haaFg" class="note-video-clip" ></iframe>

我做错了什么?

在标签名称后添加 allowfullscreen="" 的一种简单方法是修改 outerHTML of the element using string method split and array method splice,如下面的代码所示。

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

// 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(' ');
console.log(document.getElementsByTagName("iframe")[0].outerHTML);
<iframe frameborder="0" src="//www.youtube.com/embed/adLvq2haaFg" class="note-video-clip"></iframe>