简体   繁体   中英

Javascript get div by it's background image?

I have div that has this style

<div style="position:absolute;top:0px;left:0px;width:2004px;height:700px;background-color:undefined;background-image:url(https://taxirondo.net-informatika.com/wp-content/uploads/2018/04/slajder1.jpg);background-repeat:no-repeat;background-size:cover;background-position:center center;"></div>

How can I get this div and appand it with another div(by its background image)? This is automatic generated div and I can't add class or id.

One way is to get all the div s which have style assigned and then find the element which has the specified as its style.backgroundImage :

 const divs = document.querySelectorAll('div[style]'); const url = 'https://taxirondo.net-informatika.com/wp-content/uploads/2018/04/slajder1.jpg'; const elem = Array.from(divs) .find(item => item.style.backgroundImage.includes(url)); console.log(elem); 
 <div style="position:absolute;top:0px;left:0px;width:2004px;height:700px;background-color:undefined;background-image:url(https://taxirondo.net-informatika.com/wp-content/uploads/2018/04/slajder1.jpg);background-repeat:no-repeat;background-size:cover;background-position:center center;"></div> 

Please understand the implications of this code before proceeding:

  1. It does a check if the element's background contains the URL. Doesn't check the exact value.
  2. It has to iterate through the available elements to find the desired one, which may be a costly operation when there are many such elements.

You could use css attribute selector:

document.querySelector('[style*="background-image:url(https://taxirondo.net-informatika.com/wp-content/uploads/2018/04/slajder1.jpg)"]');

This way you will select the first ocurrence of an element with the supplied background image. No need to iterate thru a collection of elements.

 console.log(document.querySelector('[style="background-image:url(https://taxirondo.net-informatika.com/wp-content/uploads/2018/04/slajder1.jpg)"]')); 
 <div style="background-image:url(https://taxirondo.net-informatika.com/wp-content/uploads/2018/04/slajder1.jpg)">Selected DIV</div> 

More about attribute selectors

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM