简体   繁体   中英

How can i add a img tag inside a li tag with jQuery append

I'm trying to find a way to replace smileys :-) inside a <li> tag with jQuery.

Expecting : <li>Hi! <img class="smile"></img></li> <li>Hi! <img class="smile"></img></li>

Getting : <li>Hi! <img class="smile"></li> <li>Hi! <img class="smile"></li>

Perhaps it has something to do with the manipulation of the DOM. But unfortunately i can't figure out what i'm missing here.

<html>
    <head>
        <script src="https://code.jquery.com/jquery-latest.min.js"></script>
        <script>

            function apply_smileys(message) {
                // https://regex101.com/r/yS0eM4/1
                var regex_smile = /(:\))|(:-\))|(\(:)|(\(-:)/g;
                message = message.replace(regex_smile,'<img class="smile"></img>');
                return message;
            }

            $(document).ready(function() {
                var message = 'Hi! :)';
                message = apply_smileys(message);
                console.log(message);
                // Hi! <img class="smile"></img>
                $('<li>' + message + '</li>').appendTo('#my_list ul'); 
                // <li>Hi! <img class="smile"></li>
            });

        </script>
    </head>
    <body>
        <div id="my_list">
            <ul>
                <li>This is test</li>
            </ul>
        </div>
    </body>
</html>

You are expecting the wrong thing and you are getting the correct/valid one.

img tags are self-closing ( they cannot have a closing tag )

Quoting the MDN docs

Permitted content None, it is an empty element.
Tag omission Must have a start tag and must not have an end tag.


So it would be better to correct your code to

message = message.replace(regex_smile,'<img class="smile">');

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