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(.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.
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-informatika./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.
Share Improve this question asked May 15, 2018 at 11:55 Biljana GlumacBiljana Glumac 511 silver badge8 bronze badges 1- Does it absolutely have to be selected by the background image? Do you have nothing else at hand, like a specific position inside a specific ancestor element, or something like that? – C3roe Commented May 15, 2018 at 12:00
2 Answers
Reset to default 5You could use css attribute selector:
document.querySelector('[style*="background-image:url(https://taxirondo-informatika./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-informatika./wp-content/uploads/2018/04/slajder1.jpg)"]'));
<div style="background-image:url(https://taxirondo-informatika./wp-content/uploads/2018/04/slajder1.jpg)">Selected DIV</div>
More about attribute selectors
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-informatika./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-informatika./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:
- It does a check if the element's background contains the URL. Doesn't check the exact value.
- 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.