javascript - How to add a html element after last child of list item - Stack Overflow

I am able to add a content after last child of a list item.li:last-child:after {content: "Content&

I am able to add a content after last child of a list item.

li:last-child:after {
    content: "Content";
}

But how can I add an button or anchor after the last item,for example.

li:last-child:after {
    content: "<button id="listButtonAdd"></button>";
}

I am able to add a content after last child of a list item.

li:last-child:after {
    content: "Content";
}

But how can I add an button or anchor after the last item,for example.

li:last-child:after {
    content: "<button id="listButtonAdd"></button>";
}
Share Improve this question edited Aug 30, 2018 at 7:11 Simsons asked Aug 30, 2018 at 7:05 SimsonsSimsons 12.7k49 gold badges160 silver badges284 bronze badges 1
  • 4 Use JS for that. CSS pseudo elements are not suited for that. You will have lots of issues when trying to add events to this element – Justinas Commented Aug 30, 2018 at 7:09
Add a ment  | 

3 Answers 3

Reset to default 2

You need JS to do that, otherwise, you will be having trouble attaching actions to the created button. You can use this snippet as reference.

$("li:last-child").append(" <button id='listButtonAdd'>Some Button</button>");
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3 </li>
</ul>

you can't add tags to DOM with CSS, you should use Javascript/Jquery to insert tags to DOM, so you should use jquery append() method.

$('ul li:last').append('<button id="listButtonAdd">This is a button</button>');
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
	<li>1</li>
	<li>2</li>
	<li>3</li>
	<li>4</li>
</ul>

Following code will work

var item = document.createElement("li");
item.innerHTML = "d";
document.getElementsByClassName("list")[0].append(item)
<ul class= " list">
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745369486a4624734.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信