JavaScript:检查元素中是否存在 ::after

5
我有一个非常简单的元素:
enter image description here
如何使用Javascript检查此元素是否包含::after?(我使用document.getElementsByTagName('h2')[0]获取元素)
我不知道这个东西是如何工作的,也不需要知道,我只需要代码来检查它是否存在...
在某些情况下,该元素看起来像这样:
enter image description here
如果可能的话,我需要能够检测到这两种情况!
2个回答

1
这将是类似于这样的内容:
var pre = onload; // assign previous onload if any
onload = function(){ // onload wrapper start
if(pre)pre(); // execute previous onload in the new onload
var doc = document, h2a = doc.getElementsByTagName('h2');
var afterIn = [], afterOut = [];
for(var i=0,l=h2a.length; i<l; i++){
  var h2 = h2a[i];
  if(h2.value.match(/\:\:after/)){
    afterIn.push(h2);
  }
  else{
    afterOut.push(h2);
  }
}
for(var i=0,l=afterIn.length; i<l; i++){
  console.log(afterIn[i].value);
}
for(var i=0,l=afterOut.length; i<l; i++){
  console.log(afterOut[i].value);
}
} // onload wrapper end

document.getElementsByTagName('h2')[0].value 似乎总是未定义的。 - ManIkWeet
<head>中使用外部<script type='text/javascript' src='externalJS.js'></script>,在onload时运行它。 - StackSlave

0

1
尝试了一下,这个方法可行:当 ::after 不在的时候,window.getComputedStyle(document.querySelector('h2'), ':after').getPropertyValue('background') 的返回值是不同的,因此我可以用它来完成工作! - ManIkWeet
很高兴听到这个消息 - 我正在查看jQuery选择器(https://api.jquery.com/category/selectors/),但似乎它们没有针对此的选择器,因为它更像是CSS而不是HTML... - RebelFist

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接