Home > Net >  How do you find the next element with a specific attribute, then get that element's attribute v
How do you find the next element with a specific attribute, then get that element's attribute v

Time:07-30

Let's say I click on an element. I'm trying to get the next element with the attribute "for", then return its content (so for="Content I want").

I don't know in advance what the type of element with that attribute will be. Sometimes it's an input, sometimes a label, etc.

In my example, it's a label, but it could be an input. The clicked element would be the div.

This is my HTML:

<div  data-test="">
  <label  for="Year">Year</label>
  <input id="Year" type="number" name="Year"  placeholder="Year" required="" minlength="0" maxlength="4" value="">
  <p >Type Your Birth Year</p>
</div>

This is what I have now:

function() {
var attr = jQuery({{Click Element}}).next('[for]').attr('for');

return attr;
}

CodePudding user response:

You can use Attribute Equals Selector with jQuery

https://api.jquery.com/attribute-equals-selector/

$("[value='Test value']").click(function() {
  console.log($(this).val());
});

$("[data-test]").click(function() {
   console.log($(this).data('test')); 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" value="Test value"><br>
<button data-test="test">test data</button>

CodePudding user response:

You can do this with simple javascript, no library needed:

document.querySelectorAll('[data-foo="value"]');

let element = document.querySelectorAll('[foo="value"]');
console.log(element[0]);
<button foo="value">Submit</button>

  • Related