How to capture background value: url('URL') using jQuery?

Asked

Viewed 61 times

3

I have the following code:

<div class="chatUsers" name="chatUsers" id="1">
    <div class="chatImageUser" style="background: url('https://vignette.wikia.nocookie.net/starwars/images/2/20/LukeTLJ.jpg/revision/latest?cb=20170927034529');"></div>
    <div class="chatNomeUser">Luke Skywalker</div>
    <div class="chatStatusUser">
        <div class="chatStatusUserBall"></div>
        <div class="chatStatusUserMessage">Online</div>
    </div>
</div>

How could I capture the value of background: url('') of the element that has id=1?

I tried it this way, but it didn’t work:

var urlFoto = $("#1 > .chatImageUser").css('backgroundUrl'); 
  • Try $('.chatImageUser'). attr('style'); I’ll check another way

3 answers

4


Reference: https://stackoverflow.com/questions/8809876/can-i-get-divs-background-image-url

var urlFoto = $("#1 > .chatImageUser").css('background-image'); 
urlFoto = urlFoto.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '')
console.log(urlFoto);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="chatUsers" name="chatUsers" id="1">
    <div class="chatImageUser" style="background: url('https://vignette.wikia.nocookie.net/starwars/images/2/20/LukeTLJ.jpg/revision/latest?cb=20170927034529');"></div>
    <div class="chatNomeUser">Luke Skywalker</div>
    <div class="chatStatusUser">
        <div class="chatStatusUserBall"></div>
        <div class="chatStatusUserMessage">Online</div>
    </div>
</div>

0

It can be done as follows:

var urlFoto = $("#1 > .chatImageUser").css('backgroundUrl')
                                      .replace(/.*\s?url\([\'\"]?/, '')
                                      .replace(/[\'\"]?\).*/, '');

0

var chatImg = $('.chatImageUser').attr('style').split('//')[1]; 
chatImg = chatImg.replace("');",""); 
console.log(chatImg);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.