简体   繁体   中英

Filter link array by Jquery attr.()

I have multiple link elements in my DOM and want to search for a specific one by its href attribute.

The code that works: (removes the second link after filtering for the matching href)

 $(document).ready(() => { const ele = getLinkElementByUrl("/link2"); $(ele).remove(); }); const getLinkElementByUrl = (url) => { const links = $(".l"); // find all links var element = null; for (let i = 0; i < links.length; i++) { let ele = links[i]; let href = $(ele).attr('href'); if (href == url) { // matching href? element = ele; break; } } return element; } 
 a { text-decoration: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="l" href="/link1">Link 1</a> <br> <a class="l" href="/link2">Link 2</a> <br> <a class="l" href="/link3">Link 3</a> 

I want the code getting shorten. I tried out this code

 $(document).ready(() => { const ele = getLinkElementByUrl("/link2"); $(ele).remove(); }); const getLinkElementByUrl = (url) => { return $(".l").find(current => $(current.attr('href')) == url); } 
 a { text-decoration: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="l" href="/link1">Link 1</a> <br> <a class="l" href="/link2">Link 2</a> <br> <a class="l" href="/link3">Link 3</a> 

The search function returns me an empty array instead of the matching link element.

Is my syntax wrong?

You can try this:

 $(document).ready(() => { const ele = getLinkElementByUrl("/link2"); $(ele).remove(); }); const getLinkElementByUrl = (url) => { return $(".l[href='"+ url + "']:eq(0)"); } 
 a { text-decoration: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="l" href="/link1">Link 1</a> <br> <a class="l" href="/link2">Link 2</a> <br> <a class="l" href="/link3">Link 3</a> 

To achieve expected result, use below option of finding element using jQuery [attribute$=value] Selector

const getLinkElementByUrl = (url) => {
  return $("a[href$='/link2']")
}

code sample - https://codepen.io/nagasai/pen/LdrjVJ

 $(document).ready(() => { const ele = getLinkElementByUrl("/link2"); //console.log("ele",ele); $(ele).remove(); }); const getLinkElementByUrl = (url) => { return $("a[href$='/link2']") } 
 a { text-decoration: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="l" href="/link1">Link 1</a> <br> <a class="l" href="/link2">Link 2</a> <br> <a class="l" href="/link3">Link 3</a> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM