Any idea how to check if a div contains ONLY an image tag inside it?

Viewed 248

I've been trying to search this on stackoverflow but the answers arent exactly what im looking for, plus they use jquery. So is there any way of determing if a div element contains only an image element inside it, and therefore returning a boolean? I have tried things like:

<div className={this.find('img').length}?'hasImg':'noImg'>
 <img src=''>
  </div>

but this returned false. Even if this would work, I'd like it to return true only if there is an image regardless if there is a p tag or something else inside.

2 Answers

I am also new to this world, but messing around a little I created this:

HTML

<div class="container">
<img src="https://source.unsplash.com/random/300x300" alt="">
</div>

JS

const container = document.querySelector('.container')

const booleanResult = checkChildElement()

function checkChildElement(){
if(container.childElementCount === 1 && container.children[0].tagName === 'IMG'){
   return true
}
else{
   return false
}
}

console.log(booleanResult)

Solution

class App extends React.Component {
  state = {
    isImageExist: false,
    totalImages: 0,
    isRender: false,
  };
  checkIsImage(ref) {
    if (ref && !this.state.isRender) {
      let totalImages = Object.entries(ref.children).filter(
        ([key, child]) => child.nodeName === "IMG"
      );
      this.setState({
        totalImages: totalImages.length,
        isImageExist: totalImages.length > 0,
        isRender: true,
      });
      console.log("Total Images", totalImages.length);
    }
  }

  render() {
    return (
      <div
        ref={(ref) => {
          this.checkIsImage(ref);
        }}
      >
        <img
          src={`https://www.gravatar.com/avatar/b4185aac47f6262b40dc8f11535a32c0?s=48&d=identicon&r=PG`}
        ></img>
        <img
          src={`https://www.gravatar.com/avatar/b4185aac47f6262b40dc8f11535a32c0?s=48&d=identicon&r=PG`}
        ></img>
        <p>{this.state.totalImages}</p>
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Related