最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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>

发布评论

评论列表(0)

  1. 暂无评论