0

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...

7
  • It would be $('.myClass[href*="' + value + '"]') as there's only one element and space indicates child Commented Aug 24, 2020 at 10:11
  • Can you give an example of how you find what to look for and where it would match. "value contains the href" and "href doesn't contain value, value contains href" doesn't make much sense without some context. Commented Aug 24, 2020 at 10:12
  • 1
    I get value from window.location.pathname So if my url is in "Administration/Menus/Create" i want to select the link whose href contains "Administration/Menus". Commented Aug 24, 2020 at 10:14
  • Would you also expect to select a menu that is just href="Administration"? Or is it always just removing the last part of the path? Commented Aug 24, 2020 at 10:19
  • Only removing the last part. If not yeah I would get situations where I would get administration, or even just "A". Commented Aug 24, 2020 at 10:21

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.