Pedro Martins
Pedro Martins

Reputation: 125

CSS selector check attribute inside string

I am looking for a css selector check if a given attribute is inside a value.

For instance: I have a <a class="myClass" href="Administration/Menus"></a> and a value: Administration/Menus/Create

My goal is to select all elements where value contains the content of href.

I tried doing the following $('.myClass [href*="' + value + '"]')

But this doesnt work since my href doesnt contain value, instead value contains href...

Upvotes: 0

Views: 41

Answers (1)

fdomn-m
fdomn-m

Reputation: 28621

You can use .filter to check each if each entry matches the input.

Example input: Administration/Menus/Create

Find where href is Administration/Menus

"Only removing the last part"

Use .split, .slice and .join to remove the last part:

var lookfor = value.split("/").slice(0, -1).join("/")

then .filter with .indexOf to check if the "lookfor" part matches

var value = "Administration/Menus/Create";

var lookfor = value.split("/").slice(0, -1).join("/")
$(".myClass")
  .filter(function() {
    return lookfor.indexOf($(this).attr("href")) >= 0
  })
  .css("color", "pink")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="myClass" href="Administration/Menus">menu</a>
<a class="myClass" href="Administration/Menus/Create">create</a>
<a class="myClass" href="Administration/Menus/Delete">delete</a>

Upvotes: 1

Related Questions