简体   繁体   English

如果div包含img和src包含x则隐藏div?

[英]Hide div if it contains img with src that contains x?

If a div with id=module-120 contains an image with a source that contains: completion-auto-y I want to hide that parent div module-120 . 如果id=module-120的div包含带有源的图像,则该图像包含: completion-auto-y我想隐藏该父div module-120

This is as far as I got but it's not working. 就我所知,这是行不通的。

if (document.getElementById('#module-120')) {

    function verifyImageURL(url, callBack) {
        var img = new Image();
        img.src = url;
        img.onload = function () {
            callBack(true);
        };
        img.onerror = function () {
            callBack(false);
        };
    }

    var url = "completion-auto-y";
    verifyImageURL(url, function (imageExists) {
        if (imageExists === true) {
             document.getElementById('#module-120').style.display="none";
        } 
    });     
}

I think the problem is within the var url = "completion-auto-y" . 我认为问题出在var url = "completion-auto-y" Does someone have an idea how to fix this? 有人知道如何解决此问题吗?

Well first, let's be clear that you should only ever have one element with a given id , so you'd only need to ever hide, at most, one element. 好吧,首先,我们要明确一点,就是您只应该有一个具有给定id元素,因此,您最多只需要隐藏一个元素。

So, the solution is to use .querySelector() along with the appropriate CSS selector to get a reference to the image that has a parent that should be hidden. 因此,解决方案是将.querySelector()与适当的CSS选择器一起使用,以获取对具有应隐藏的父对象的图像的引用。 Then hide the parent element. 然后隐藏父元素。

 // Get the image that matches the criteria let match = document.querySelector("div[id='module-120'] img[src*='completion-auto-y']"); match.parentNode.classList.add("hidden"); // Hide the parent element 
 .hidden { display:none; } 
 <div id="module-120"> <img src="completion-auto-x"> I should not be hidden </div> <div id="module-120"> <img src="completion-auto-y"> I should be hidden </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM