如何将标签中的链接传递a
给通过追加创建的相应新链接?
let heading = document.querySelectorAll(".heading");
let map = new Map();
for (let i = 0; i < heading.length; ++i) {
let a = heading[i].querySelectorAll("a");
let groupName = a[0].textContent.trim();
for (let j = 1; j < a.length; ++j) {
let companyName = a[j].textContent.trim();
let href = a[j].href;
let companyGroups = map.get(companyName);
if (companyGroups) companyGroups.push({ groupName, href });
else map.set(companyName, [{ groupName, href }]);
}
}
let compare = (new Intl.Collator("ru")).compare;
let ul = document.createElement("ul");
ul.className = "some-style";
let companies = Array.from(map.keys()).sort(compare);
for (let companyName of companies) {
let li = document.createElement("li");
let a = document.createElement("a");
a.textContent = companyName;
li.append(a);
let li_ul = document.createElement("ul");
let companyGroups = map.get(companyName).sort(compare);
for (let groupName of companyGroups) {
let li = document.createElement("li");
let a = document.createElement("a");
a.textContent = groupName;
li.append(a);
li_ul.append(li);
}
li.append(li_ul);
ul.append(li);
}
document.querySelector('.input').append(ul);
.some-style {
background-color: silver;
border: 1px solid black;
}
.hide {
display: none;
}
<div class="input"><div>
<ul class="hide">
<li class="heading"><a href="google.com/samsung">Телевизоры</a>
<ul>
<li><a href="google.com/samsung" href="google.com/samsung">Samsung</a></li>
<li><a href="google.com/samsung" href="google.com/samsung">Lenovo</a></li>
</ul>
</li>
<li class="heading"><a href="google.com/samsung">Планшеты</a>
<ul>
<li><a href="google.com/lenovo-03">Lenovo</a></li>
<li><a href="google.com/samsung">Samsung</a></li>
<li><a href="google.com/acer-43">Acer</a></li>
</ul>
</li>
<li class="heading"><a>Ноутбуки</a>
<ul>
<li><a href="google.com/lenovo-83">Lenovo</a></li>
<li><a href="google.com/samsung-323">Samsung</a></li>
<li><a href="google.com/acer-021">Acer</a></li>
</ul>
</li>
</ul>
1 个回答