Reputation: 51
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
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
Reputation: 23859
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:
Upvotes: 4