如何在li标签中设置href属性?

时间:2019-05-17 11:48:54

标签: javascript html css

我正在编码一个内部网。

我用HTML编写了代码。现在,我将用JS重写HTML代码,以便可以动态添加,修改和删除某些内容。

我必须使用mySection.setAttribute("class", "myClass");为我的标签提供类,id,...。 当只有一个类或一个id时,就没有问题。但是现在我必须用JS重写这一行:

<li><a href="https://www.google.ch/" target="_blank">Yahoo</a></li>

我无法解决我一直在尝试并在互联网上搜索的问题...但是似乎没有什么比我的问题更重要的。

2 个答案:

答案 0 :(得分:2)

你是说

// Create new links

var ul = document.getElementById("linkList"),
    li = document.createElement("li"), 
     a = document.createElement("a"); 
a.href="https://www.google.ch/";  // or a.setAttribute("href","https://www.google.ch/");
a.target="_blank"; 
a.innerText="Yahoo"; 
li.appendChild(a); 
ul.appendChild(li);

// If you need to change the link and it does not have any class, you can do something like
document.querySelectorAll("#linkList li > a[target=_blank]").forEach(lnk => {
  lnk.className = "red";
  // more classes? 
  lnk.classList.add("no_underline");
});  
.red { color:red }
.no_underline { text-decoration:none }
<ul id="linkList">
<li><a href="https://developer.mozilla.org/" target="_blank">MDN</a></li>
</ul>

答案 1 :(得分:0)

这可能有助于实现您的目标。

<script>
$(document).ready(function(){
  var a =document.querySelector("a[href$='.ch']");
  a.setAttribute("class", "democlass");
});
</script>
相关问题