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

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 do to catch the value of background: url('') of the element that has id=1 ?

I tried the following, but it did not work:

var urlFoto = $("#1 > .chatImageUser").css('backgroundUrl'); 
    
asked by anonymous 16.03.2018 / 17:54

3 answers

4

Reference: link

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><divclass="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>
    
16.03.2018 / 17:59
0
var chatImg = $('.chatImageUser').attr('style').split('//')[1]; 
chatImg = chatImg.replace("');",""); 
console.log(chatImg);
    
16.03.2018 / 18:11
0

It can be done as follows:

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