簡體   English   中英

如果它沒有類或ID,是否可以通過其href獲取鏈接?

[英]Is it possible to grab a link by its href if it doesn't have a class or ID?

我正在使用其他人的應用程序,並希望更改具有特定href的任何<a> </ a>標記之間的innerHTML。 但是這些鏈接沒有與它們相關聯的類或ID,我無法編輯代碼來為它們提供類或ID。 有沒有辦法在JavaScript中通過href獲取標記? 我想做類似的事情:

var theLink = document.getElementByHref("example.com");

否則,如果不可能,我可以遍歷頁面中的所有鏈接,並選擇那些具有我正在尋找的特定href和innerHTML的鏈接嗎?

您可以使用DOM3屬性選擇器( jQuery doc )來獲取其href屬性中包含特定文本的所有元素。 它看起來像

$('a[href*="example.com"]')

但是,這可能不是您真正想要的 - 不僅僅是該域的URL可能包含此字符串。 你可以做一些像開頭一樣的事情:

$('a[href^="http://example.com"]')

但要獲得精確且可能更復雜的匹配,您無需繞過自定義過濾器

$('a[href]').filter( function() {
     return this.hostname == "example.com";
     // or check other properties of the anchor element
})

選擇href屬性中包含example.com值的所有元素:

現場演示: http //jsfiddle.net/NTGQz/

$('a[href*="example.com"]');

你也可以嘗試這個,只是為了更具體,並遵循OP “理想”的答案:

現場演示: http //jsfiddle.net/ksZhZ/

jQuery.fn.getElementsByHref = function(str){ return $('a[href*="' + str + '"]'); };

$(document).ready(function(){        
   elems = $(this).getElementsByHref('example.com');
});

jQuery有很多選擇器 你想要的是屬性選擇器。

$('a[href="example.com"')

您可以使用屬性選擇器:

$('a[href="http://example.com"]')

使用JQuery 屬性選擇器 ,您可以執行以下操作:

$('a[href="example.com"]')

嘗試這個

$('a[href*="example.com"]');

這將選擇href屬性中包含example.com的鏈接。

$('a[href="http:google.com"]')

你可以用jquery做到這一點: http//api.jquery.com/attribute-equals-selector/

例如:linksToGoogle = $('a [href =“http://google.com”]');

沒有jQuery你可以做到這一點。

var links = document.querySelectorAll('a[href*="example.com"]');

如果您的用戶在IE8 +或任何其他瀏覽器上,您可以使用querySelectorAll本機執行此操作。 此方法返回匹配元素的NodeList

document.querySelectorAll('a[href="exact/value.html"]');    // exact match
document.querySelectorAll('a[href*="partial/value.html"]'); // partial match
document.querySelectorAll('a[href^="starts/with"]');        // href starts with
document.querySelectorAll('a[href$=".html"]');              // href ends with

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM