Skip to content
Advertisement

How to get DIV sub-elements using javascript

HTML Code

<ins class="adsbygoogle" style="display:inline-block;width:336px;height:280px" data-ad-client="ca-pub-1714167228247329" data-ad-slot="8611448539" data-adsbygoogle-status="done" data-ad-status="unfilled">

I have checked : https://www.w3schools.com/js/js_htmldom_elements.asp and tried but it not help.

I want to take this element data-ad-status="unfilled" from HTML using javascript. So, i can use it in if else statement.

Like

if (data-ad-status="unfilled") {
some fuctions; 
}

Advertisement

Answer

  • As you told me that data is coming from async way I have added setTimeOut() function to wait for around 2 seconds here.
  • I do not have access to how data is coming so this time for 2s is hard coded. change it’s value and try to run it. and I am sure it will solve your problem.
  • But use asyn-await function and make selectAd() wait till you data get loaded.

const selecteAd = () => {
  const myDiv = document.querySelector("[data-ad-status='unfilled']");
  const selectAllWithAttributeAdStatus = document.querySelectorAll("[data-ad-status]");
  /*This(selectAllWithAttributeAdStatus) one is just for showing how to select elements with data-ad-status attribute */
  //let adStatus = myDiv.getAttribute("data-ad-status");
  selectAllWithAttributeAdStatus.forEach(ad => {
    if ((ad.getAttribute("data-ad-status")) === "unfilled") {
      ad.style.background = "red";
      ad.style.height = "100px";
      ad.style.width = "100px";
      ad.style.display = "inline-block";
    } else {
      ad.style.background = "green";
      ad.style.height = "100px";
      ad.style.width = "100px";
      ad.style.display = "inline-block";
    };
  })
}
const myTimeout = setTimeout(selecteAd, 2000);
<div class="adsbygoogle" style="display:inline-block;width:336px;height:280px" data-ad-client="ca-pub-1714167228247329" data-ad-slot="8611448539" data-adsbygoogle-status="done" data-ad-status="unfilled"></div>
<div class="adsbygoogle" style="display:inline-block;width:336px;height:280px" data-ad-client="ca-pub-1714167228247329" data-ad-slot="8611448539" data-adsbygoogle-status="done" data-ad-status="somethingelse"></div>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement