Question3r
Question3r

Reputation: 3782

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?

Upvotes: 0

Views: 46

Answers (2)

Marc
Marc

Reputation: 1467

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>

Upvotes: 1

Naga Sai A
Naga Sai A

Reputation: 10975

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>

Upvotes: 1

Related Questions