Biljana Glumac
Biljana Glumac

Reputation: 51

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.

Upvotes: 2

Views: 1845

Answers (2)

muecas
muecas

Reputation: 4335

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

Upvotes: 5

31piy
31piy

Reputation: 23859

One way is to get all the divs 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.

Upvotes: 4

Related Questions