Home > Blockchain >  How to find a class element inside each li using jQuery
How to find a class element inside each li using jQuery

Time:05-25

How to find the element with class spotlight-img-blk inside each li using jQuery and add the background dynamically?

<div >
    <div >
        <ul>
            <li>
                <div >
                    <div  data-bg="home-blog1-bg.jpg"></div>
                </div>
            </li>
            <li>
                <div >
                    <div  data-bg="home-blog2-bg.jpg"></div>
                </div>
            </li>
            <li>
                <div >
                    <div  data-bg="home-blog2-bg.jpg"></div>
                </div>
            </li>
        </ul>
    </div>
</div>

CodePudding user response:

$s('.spotlight-blk-outer li').each(function(){
var element = $s(this)
var imageEle = $s('.spotlight-img-blk', element)
var imgText = imageEle.data('bg')
imageEle.css('background-image', 'url('   hostUrl   '/wp-content/themes/themeName/images/blog-images/'   imgText   ')')})

CodePudding user response:

This seems simpler.

$(".spotlight-blk-outer .spotlight-img-blk").each(function() { 
  const img = `${hostUrl}/wp-content/themes/themeName/images/blog-images/${this.dataset.bg}`;
  $(this).closest(".spotlight-inner-blk").css({"backgroundImage": `url(${img})`});
});
<div >
  <div >
    <ul>
      <li>
        <div >
          <div  data-bg="home-blog1-bg.jpg"></div>
        </div>
      </li>
      <li>
        <div >
          <div  data-bg="home-blog2-bg.jpg"></div>
        </div>
      </li>
      <li>
        <div >
          <div  data-bg="home-blog2-bg.jpg"></div>
        </div>
      </li>
    </ul>
  </div>
</div>

Plain JS

document.querySelectorAll(".spotlight-blk-outer .spotlight-img-blk").forEach(function() { 
  const img = `${hostUrl}/wp-content/themes/themeName/images/blog-images/${this.dataset.bg}`;
  this.closest(".spotlight-inner-blk").style.backgroundImage = `url(${img})`;
});  
<div >
  <div >
    <ul>
      <li>
        <div >
          <div  data-bg="home-blog1-bg.jpg"></div>
        </div>
      </li>
      <li>
        <div >
          <div  data-bg="home-blog2-bg.jpg"></div>
        </div>
      </li>
      <li>
        <div >
          <div  data-bg="home-blog2-bg.jpg"></div>
        </div>
      </li>
    </ul>
  </div>
</div>

  • Related