简体   繁体   中英

Setting background image dynamically ul/li div element

I am new in website development and trying to figure out how to set image dynamically in ul / li div element. Below is my code in html file :

<div class="results">
    <ul class="row">
        <li class="template hidden col-md-3">
            <div class="image">
                <!--img src='broken_file.png'-->
                <data>
                    <span class="name"></span>
                    <span data-before='faces' class="faces"></span>
                    <span data-before='genus' class="genus"></span>
                    <span data-before='vertices' class="vertices"></span>
                </data>
            </div>
        </li>
    </ul>
</div>

And from another js file I am trying to access the 'image' div as

$(li).find('image').css()

I am trying to set an image url inside css() , but not sure how I can do it, or even it is possible?

Firstly your jQuery syntax is incorrect. li should be in quotes as it's a string, and the image selector requires a preceding . as it's a class. Finally, you can set the background-image in CSS, like this:

$('li').find('.image').css('background-image', 'url("my-image.png")');

1) If you want to insert img tag into div with "image" class -

$('li').find('.image').append($('<img src="http://fakeimg.pl/250x100/000/">'))

2) If you want to change src attr -

    $('li').find('.image img').attr('src','http://fakeimg.pl/250x100/000/">')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM