我在运行时填充div的数据,我需要检查元素是否存在。
我在SO中看到了一些有关如何操作的提示。
我在DOM中有
<div id="messages">
<div class="direct-chat-msg right" data-msg-id="true_5521971319071@c.us_AB57E3CC69662AC4059250385929DD72">
<div class="direct-chat-info clearfix">
<span class="direct-chat-name pull-right"></span>
</div>
</div>
</div>
现在,我需要测试元素是否存在。我已经尝试了下一个,但是都没有用:
document.querySelectorAll('[data-msg-id="true_5521999957988@c.us_26B99C7B58A653A4FFCFBD1DFF92498D"]').length>0
和
$("body").find(`[data-msg-id='${"true_5521999957988@c.us_26B99C7B58A653A4FFCFBD1DFF92498D"}']`).length>0
答案 0 :(得分:1)
我看到您在这里有一个true
前缀:使用正则表达式(而不是整个ID)呢?
JS:
document.querySelectorAll('div[data-msg-id="^true"]') ? foo : bar;
jQuery:
$('body').find('div[data-msg-id="^true"') ? foo : bar;
我不知道您是否必须匹配确切的值,但这应该会有所帮助。当然,如果您有更多实例并且要检查第一个实例,则必须相应地更改代码。
答案 1 :(得分:0)
您还可以执行以下操作:
const dataValue = document.getElementsByClassName("direct-chat-msg right");
if (dataValue[0].hasAttribute("data-msg-id")) {
console.log(true);
} else {
console.log(false)
}