如何删除div标签下列出的href?

时间:2017-01-17 00:36:01

标签: javascript html css wordpress

我正在修改wordpress主题的一部分而且我遇到了一个问题。我想删除点击链接的功能,虽然我没有能力修改类名或设置ID标签

HTML:

<div class="one">
  <a href="foobar.com">foobar.com</a>
</div>

我尝试通过编写此JavaScript来删除该功能:

document.getElementsByClassName("one")
  .getElementsByTagName("a")
  .removeAttribute("href");

然而这种方法不起作用,我做错了吗?

6 个答案:

答案 0 :(得分:3)

你可以使用css。

.one a {
    pointer-events: none;
  }

您还可以通过添加cursor: default;

来移除手形光标

答案 1 :(得分:2)

document.getElementsByTagName("a")[0].removeAttribute("href");
<div class="one">
    <a href="foobar.com">foobar.com</a>
</div>

无需首先定位.one。只需按getElementsByTagName定位,但请记住这会返回一个元素数组,因此您需要引用要删除的元素的索引。

document.getElementsByTagName("a")[0].removeAttribute("href");

答案 2 :(得分:0)

如果您只需要选择“one”类中的链接,则需要索引从getElementsByClass返回的内容,然后调用children并将其编入索引:

document.getElementsByClassName("one")[0].children[0].removeAttribute("href")

答案 3 :(得分:0)

你可以这样做:

     document.getElementById("text").onclick = function(){
		
    var clickStatus = true; // Change this to true if you want to enable the link.
		
	if (clickStatus){
   	  window.location = "http://foobar.com";
	}
			
}
<div class="one">
   <section id="text">foobar.com</section>
</div>

答案 4 :(得分:0)

它将生成Type Error,因为getElementsByClassName函数将返回节点列表而不是单个节点,因此您需要执行以下操作:

document.getElementsByClassName("one")[0]
.getElementsByTagName("a")[0]
.removeAttribute("href");

document.querySelector(".one a").removeAttribute("href");

上述任何方法都可以解决您的问题

我希望它有所帮助

答案 5 :(得分:0)

我认为你需要在这里禁用Href功能。 请使用Jquery:

$('.one > a').on('click',function(e){    
  e.preventDefault();
}

希望这对你有用

相关问题