const slidesLength = slideRight.querySelectorAll('div').length / 2;
<div >
<div style="background-color: #773f47bd">
<div style="background-image: url(/pic1.jpg);"></div>
</div>
<div style="background-color: #773f47bd">
<div style="background-image: url(/pic2.jpg);"></div>
</div>
<div style="background-color: #773f47bd">
<div style="background-image: url(/pic3.jpg);"></div>
</div>
<div style="background-color: #773f47bd">
<div style="background-image: url(/pic4.jpg);"></div>
</div>
<div style="background-color: #773f47bd">
<div style="background-image: url(/pic5.jpg);"></div>
</div>
</div>
I am trying to target the inner most using querySelectorAll(), but I am unsure of how to do that. With the JS code I have right now, I am able to to get the exact number of divs I want, but only by using a different method. I was wondering whether or not there is a way where I can disregard the divs with background-color and only obtain the ones with background image. Thank you.
CodePudding user response:
Yes, document.querySelectorAll('.right-slide div[style*=background-image]') will get a list together of all divs inside of .right-slide that have a background-image as an inline style
const bgImageDivs = document.querySelectorAll('.right-slide div[style*=background-image]');
console.log(bgImageDivs)
<div >
<div style="background-color: #773f47bd">
<div style="background-image: url(/pic1.jpg);"></div>
</div>
<div style="background-color: #773f47bd">
<div style="background-image: url(/pic2.jpg);"></div>
</div>
<div style="background-color: #773f47bd">
<div style="background-image: url(/pic3.jpg);"></div>
</div>
<div style="background-color: #773f47bd">
<div style="background-image: url(/pic4.jpg);"></div>
</div>
<div style="background-color: #773f47bd">
<div style="background-image: url(/pic5.jpg);"></div>
</div>
</div>
CodePudding user response:
You could use a for loop to check it if the div has background-image or not.
let div = document.querySelectorAll('div');
let num =0;
for(let i =0;i<div.length;i ){
if(div[i].style.backgroundImage !=='')
num
}
console.log(num)
<div >
<div style="background-color: #773f47bd">
<div style="background-image: url(/pic1.jpg);"></div>
</div>
<div style="background-color: #773f47bd">
<div style="background-image: url(/pic2.jpg);"></div>
</div>
<div style="background-color: #773f47bd">
<div style="background-image: url(/pic3.jpg);"></div>
</div>
<div style="background-color: #773f47bd">
<div style="background-image: url(/pic4.jpg);"></div>
</div>
<div style="background-color: #773f47bd">
<div style="background-image: url(/pic5.jpg);"></div>
</div>
</div>
