我试图编写一个简单的脚本,它将改变页面上许多锚点的文本。我对Javascript很陌生,我能够更改锚点,但它会更改整个标记,包括删除href。
如何仅编辑文本而不影响href?
<body>
<div class="loop-add-to-cart">
<a href="/?preview_id=10822&preview_nonce=2f9a98329f&_thumbnail_id=-1&preview=true&add-to-cart=11544" rel="nofollow" data-product_id="11544" data-product_sku="" data-quantity="1" class="add_to_cart_button product_type_simple ajax_add_to_cart">Add to basket</a>
<div class="wpd-buttons-wrap-simple" data-id="11544">
<a href="http://802.f5f.myftpupload.com/11550-2/design/11544/" class="mg-top-10 wpc-customize-product">Design from blank</a>
</div>
</div>
<script>
function buybuttons() {
var buybuttons = document.getElementsByClassName('wpd-buttons-wrap-simple');
for(var i = 0; i < buybuttons.length; i++){
buybuttons[i].innerHTML="Test";
};
}
buybuttons();
</script>
</body>
答案 0 :(得分:0)
使用'querySelectorAll',您可以获取元素类和内部元素,如下所示:
document.querySelectorAll('.wpd-buttons-wrap-simple > a')
答案 1 :(得分:0)
function buybuttons() {
var buybuttons = document.querySelectorAll('.wpd-buttons-wrap-simple a');
for(var i = 0; i < buybuttons.length; i++){
buybuttons[i].innerHTML="Test";
};
}
buybuttons();
您目前正在覆盖div元素的innerHTML,但是您正在寻找div内部的anchor元素。
使用document.querySelectorAll来获取所有这些,或者使用document.querySelector来获取第一个。
答案 2 :(得分:0)
您可以使用查询选择器来获取元素为a
的元素内的所有wpd-buttons-wrap-simple
标记:
document.querySelectorAll('.wpd-buttons-wrap-simple a');
然后您可以设置链接的textContent
或innerHTML
。
<body>
<div class="loop-add-to-cart">
<a href="/?preview_id=10822&preview_nonce=2f9a98329f&_thumbnail_id=-1&preview=true&add-to-cart=11544" rel="nofollow" data-product_id="11544" data-product_sku="" data-quantity="1" class="add_to_cart_button product_type_simple ajax_add_to_cart">Add to basket</a>
<div class="wpd-buttons-wrap-simple" data-id="11544">
<a href="http://802.f5f.myftpupload.com/11550-2/design/11544/" class="mg-top-10 wpc-customize-product">Design from blank</a>
</div>
</div>
<script>
function buybuttons() {
var buybuttons = document.querySelectorAll('.wpd-buttons-wrap-simple a');
for(var i = 0; i < buybuttons.length; i++){
buybuttons[i].textContent = "Test";
};
}
buybuttons();
</script>
</body>