简体   繁体   中英

How to append a div with script tag into an li tag?

We have a <ul> with many <li> tags that is used for a menu links. How can we append the following code to the end of the <ul> ?

Problem:

My current code is not adding even the <div> tag.

Goal: Always append the <li><div><script></script></div></li> as the very last item of the <ul class="menu" id="footer-menu"> by first creating the <script> tag and then appending it to the newly created <div> tag and then finally appending it to the end of the <ul> tag.

Current output:

<ul class="menu" id="footer-menu">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>

Desired output:

<ul class="menu" id="footer-menu">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li><div id='somevalue'><script async="async" crossorigin type="text/javascript" src="some-src"></script></div></li>
</ul>

 (function() { var scriptTag = document.createElement('script'); scriptTag.type="text/javascript"; scriptTag.async=true; scriptTag.crossOrigin=true; scriptTag.src="some-source"; var divTag = document.createElement('div'); divTag.id='somevalue'; divTag.append(scriptTag); var ulList = document.getElementById('footer-menu'); ulList.append(divTag); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="menu" id="footer-menu"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> 

You are not calling the anonymous function, use this instead:

 (function() { var scriptTag = document.createElement('script'); scriptTag.type="text/javascript"; scriptTag.async=true; scriptTag.crossOrigin=true; scriptTag.src="some-source"; var divTag = document.createElement('div'); divTag.id='somevalue'; divTag.append(scriptTag); var liTag = document.createElement('li'); liTag.append(divTag); var ulList = document.getElementById('footer-menu'); ulList.append(liTag); })(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="menu" id="footer-menu"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> 

Use the lastChild property of the ul.

Try changing the last line to:

ulList.lastChild.append(divTag);

以下解决方案会将带有script标签的div附加到所需的li标签中:

$("#footer-menu li").last().append('<div id="somevalue"><script async="async" crossorigin type="text/javascript" src="some-src"></script></div>');

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