I have html code below:
<li class="name1 name2 name3" data-animate-effect="fadeIn" style="background-image: url(images/gallery-1.jpg); ">
Then how to set images/gallery-1.jpg
to my imageURL
variable javascript by querySelector? This is my try and error:
let imageURL = gallery[newIndex].querySelector("li").style.background.url;
CodePudding user response:
A little more code needed
You can change document.querySelector("[data-animate-effect]")
to gallery[newIndex].querySelector("li")
if preferred
console.log(document.querySelector("[data-animate-effect]")
.style.backgroundImage.match(/"(.*)"/)[1])
<li class="name1 name2 name3" data-animate-effect="fadeIn" style="background-image: url(images/gallery-1.jpg); ">
CodePudding user response:
Select the item, get the computed style, and retrieve the background image information. Then extract the URL from that data with a regular expression, and match
.
const li = document.querySelector('li');
const style = window.getComputedStyle(li);
const imageUrl = style.getPropertyValue('background-image');
console.log(imageUrl.match(/"(. )"/)[1]);
<li class="name1 name2 name3" data-animate-effect="fadeIn" style="background-image: url('https://dummyimage.com/100x100/666/ff0'); ">
CodePudding user response:
Use .replace() to regular expressions when possible, since it's often easier to read:
javascript code
var image = $("li").css("background-image")
image = image.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '')
Output:
images/gallery-1.jpg