如何在现有的li标签内添加Anchor标签

时间:2019-07-04 12:34:32

标签: javascript html

所以我的问题很简单,但是我一直在努力寻找答案。

我已经创建了一个列表,我想在<li>标签内添加一个标签,然后使用JS将setAttribute添加到该<a>标签中:

<ul>
  <li>one</li> <!-- This is what a have right now -->
  <li><a href="#HTML">one</a></li> <!-- This is what I want -->
</ul>

3 个答案:

答案 0 :(得分:0)

"use strict";
// This first line you most probably have to change according to your context
// This get the first element of all the li tags in the whole document
const li = document.getElementsByTagName('li')[0]
// This gets the text content ('one') of that 'li'
const tc = li.textContent
// This removes the first child content of li, which is the text
li.childNodes[0].remove()
// This will create a new 'a' element, set the href attribute, insert the text from above into it
// and that insert this 'a' into the 'li'
const a = document.createElement('a')
a.textContent = tc
a.setAttribute('href', '#HTML')
li.append(a)
<ul>
  <li>one</li>
</ul>

答案 1 :(得分:-1)

// select the <li>
const li = document.querySelector('li');

// create the <a>
const a = document.createElement('a');
a.href='#html';
a.innerText = li.innerText;

// empty <li> and replace its content by <a>
li.innerHTML = '';
li.appendChild(a);
<ul>
  <li>one</li>
</ul>

答案 2 :(得分:-1)

这可以通过JS通过以下方式实现。但我建议您在a标签中添加一个标识符,例如一个类,因为这将获得文档中的第一个元素:

document.querySelector('a').setAttribute('href', '#HTML');

这是一种更好的方法(JS):

document.querySelector('.myLink').setAttribute('href', '#HTML');

HTML:

<a class="myLink">one</a>