document.getElementsByClassName()类标识符更改

问题描述 投票:0回答:1

我有一个脚本,可在Google的一种工具的用户界面中插入iFrame。最近进行了更新,此特定工具具有新外观。

[我注意到,每次创建新列表时类名都会更改,就像这样,

第一列表

类别名称1:header _ngcontent-CREATIVES-69

类别名称2:_ngcontent-CREATIVES-71

第二列表

类别名称1:header _ngcontent-CREATIVES-68

类别名称2:_ngcontent-CREATIVES-70

我如何使我的脚本起作用,以便仅以这种方式识别它?

类别名称1:header _ngcontent-CREATIVES-XX

类别名称2:_ngcontent-CREATIVES-XX

我正在处理的脚本,

var xhttp=new XMLHttpRequest,
RespJSON=null;

function setvalues(t){
  ifrm=document.createElement("iframe"),
  ifrm.setAttribute("style","margin-top: -240px;width: 100%;height: 450px;"),
  ifrm.setAttribute("scrolling","no"),
  ifrm.src="#"+escape(t),
  document.getElementsByClassName("header _ngcontent-CREATIVES-69")[0].append(ifrm)
}
xhttp.onreadystatechange=function(){
  4==this.readyState&&200==this.status&&setvalues(RespJSON=xhttp.responseText)
},

xhttp.open("GET",document.getElementsByClassName("_ngcontent-CREATIVES-71")[0].src,!0),
xhttp.send();

什么是解决这个问题的好方法?

javascript getelementsbyclassname
1个回答
0
投票

您可以使用querySelectorquerySelectorAll通过属性选择器选择DOM元素

document.querySelector("[class^=\"header _ngcontent-CREATIVES-\"]").append(ifrm)

这将选择第一个以header _ngcontent-CREATIVES-开头的类的DOM元素>

OR

document.querySelectorAll("[class^=\"header _ngcontent-CREATIVES-\"]")[0].append(ifrm)

示例:https://jsfiddle.net/ydz69kwp/

© www.soinside.com 2019 - 2024. All rights reserved.