Javascript如何更改href

时间:2016-12-29 16:28:49

标签: javascript

function PressMe(){   
    var elements = document.getElementsByClassName("navigation");
    for (var i = 0; i < elements.length; i++){
         elements[i].href = "#HTML";    
    }   
} 

尝试使用纯JavaScript创建一个应该执行以下操作的函数,但我遗漏了一些东西而且我不确定是什么。

<li class="navigation">HTML</li> 

应改为

<li class="navigation><a href="#HTML">HTML</a></li> 

有三个列表元素。

已经设法使用jQuery但需要在JavaScript中使用它。

{
    $(".navigation").wrapInner("<a href='#HTML'></a>");
});

3 个答案:

答案 0 :(得分:2)

问题:当您执行elements[i].href = "#HTML"时,您正尝试将href直接设置为li .nvigation

建议的解决方案:获取每个li href元素的文本,然后使用li创建包含此文本的新锚,然后使用.innerHTML将其附加到for (var i = 0; i < elements.length; i++){ var text = elements[i].innerText; elements[i].innerHTML = "<a href='#"+text+"'>"+text+"</a>"; } function PressMe() { var elements = document.getElementsByClassName("navigation"); for (var i = 0; i < elements.length; i++) { var text = elements[i].innerText; elements[i].innerHTML = "<a href='#"+text+"'>"+text+"</a>"; } }

<ul>
  <li class="navigation">HTML</li> 
  <li class="navigation">TEST</li> 
  <li class="navigation">TEXT</li>
</ul>

<button type='button' onclick='PressMe()'>Press Me </button>

希望这有帮助。

{{1}}
{{1}}

答案 1 :(得分:1)

&#13;
&#13;
function PressMe() {   
  var elements = document.getElementsByClassName("navigation");

  for (var i = 0; i < elements.length; i++) {
    var link = document.createElement("a");
    
    link.href = "#" + elements[i].innerText;
    link.innerText = elements[i].innerText;

    elements[i].innerText = ""; 
    elements[i].appendChild(link);
  }   
} 

PressMe();
&#13;
<ul>
  <li class="navigation">HTML</li> 
  <li class="navigation">CSS</li> 
  <li class="navigation">JAVASCRIPT</li> 
</ul>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

所以选择元素的文本,然后添加锚

&#13;
&#13;
var elements = document.getElementsByClassName("navigation");
for (var i = 0; i < elements.length; i++) {
  var html = elements[i].innerHTML
  elements[i].innerHTML = '<a href="#' + html + '">' + html + '</a>';
}
&#13;
<ul>
  <li class="navigation">HTML</li>
  <li class="navigation">FOO</li>
  <li class="navigation">BAR</li>
  <li class="navigation">WORLD</li>
</ul>
&#13;
&#13;
&#13;

或者您可以使用createElement并将其附加到li。

&#13;
&#13;
var elements = document.getElementsByClassName("navigation");
for (var i = 0; i < elements.length; i++) {
  var li = elements[i];
  var html = li.innerHTML;
  li.innerHTML = "";
  var anchor = document.createElement("a");
  anchor.innerHTML = html;
  anchor.href = "#" + html;
  li.appendChild(anchor);
}
&#13;
<ul>
  <li class="navigation">HTML</li>
  <li class="navigation">FOO</li>
  <li class="navigation">BAR</li>
  <li class="navigation">WORLD</li>
</ul>
&#13;
&#13;
&#13;