Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get array of elements having specific href attribute

I need array of elements (inside story) having href attribute starts with view.php.

Here are my tryings, without success:

let arr = $('#story').find(".el[href.startsWith('view.php')]");
//let arr = $('#story').find(".el[attr('href').startsWith('view.php')]");

console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='story'>
<a class='el' href = 'view.php?id=323'>lorem</a>
<a class='el' href = 'about.php'>ipsum</a>
<a class='el' href = 'index.php'>lorem</a>
<a class='el' href = 'view.php?id=525'>ipsum</a>
</div>
like image 485
qadenza Avatar asked Mar 05 '26 07:03

qadenza


2 Answers

You can use a[href^="view.php"] starts with attribute selector and then get array of href values with map and get methods.

let arr = $('#story a[href^="view.php"]').map(function() {
  return $(this).attr('href')
}).get()

console.log(arr)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='story'>
  <a class='el' href='view.php?id=323'>lorem</a>
  <a class='el' href='about.php'>ipsum</a>
  <a class='el' href='index.php'>lorem</a>
  <a class='el' href='view.php?id=525'>ipsum</a>
</div>
like image 153
Nenad Vracar Avatar answered Mar 07 '26 20:03

Nenad Vracar


document.querySelectorAll('#story > a[href^="view.php"]')

like image 39
samb102 Avatar answered Mar 07 '26 22:03

samb102



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!