querySelector()
is the DOM API method that you should use.
You should use this instead of querySelectorAll()
(as some have mentioned) as this will perform better because it only looks for a single match and stops after finding one. Depending on the depth of your DOM, using querySelector()
instead of querySelectorAll()
or getElementsByTagName()
can positively impact performance of the code.
This snippet shows a simple function that you can call anytime you need to do this check. If a nested <img>
element is found, then you have a "truthy" result that you can test for with an if
and if no nested <img>
is found, then you have a "falsy" result that the same if
condition can test for.
// Get DOM references to the wrappers you wish to test:
var wrap1 = document.getElementById("wrapper");
var wrap2 = document.getElementById("wrapper2");
// General function to test any DOM element for a descendant image.
function testImage(wrap){
// querySelector will return the first element that matches the query
// If no element is matched, no element is returned (null)
// Using the JavaScript "ternary" operator here to test the "truthy" or
// "falsy" result of querySelector on the supplied DOM object. If there is
// a nested image message becomes an empty string, but if there is no nested
// image, message becomes " not". Of course, you can change this to any
// values/operations you want to perform based on the result of the test.
var message = wrap.querySelector("img") ? "" : " not";
// Write a message and use the string determined in the previous line:
console.log("There is" + message + " an image inside " + wrap.id)
}
// Run the function as often as you liike:
testImage(wrap1);
testImage(wrap2);
<div id="wrapper">
</div>
<div id="wrapper2">
<img src="" alt="">
</div>