Josianne Tl
Josianne Tl

Reputation: 1

How do you find the next element with a specific attribute, then get that element's attribute value?

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 class="styled-placeholder quarter InputText" data-test="">
  <label class="input-label" for="Year">Year</label>
  <input id="Year" type="number" name="Year" class="input-control required" placeholder="Year" required="" minlength="0" maxlength="4" value="">
  <p class="errors-input">Type Your Birth Year</p>
</div>

This is what I have now:

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

return attr;
}

Upvotes: 0

Views: 183

Answers (3)

Reza Saadati
Reza Saadati

Reputation: 5419

Your mistake is that you are looking for the next element. Based on your HTML that you have provided, there is no next element. So the element with the for attribute is a child element.

This is how you could get the first child element with attribute for:

$('div').on('click', function(e) {
  const el = $(this).children('[for]')[0];
  console.log('Attribute value: ' + $(el).attr('for'));
  console.log('Content: ' + $(el).html());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="styled-placeholder quarter InputText" data-test="">
  <label class="input-label" for="Year">The Year</label>
  <input id="Year" type="number" name="Year" class="input-control required" placeholder="Year" required="" minlength="0" maxlength="4" value="">
  <p class="errors-input">Type Your Birth Year</p>
</div>

Upvotes: 1

SKJ
SKJ

Reputation: 2326

You can use Attribute Equals Selector with jQuery

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

$("[value='Test value']").click(function() {
  console.log($(this).nextAll("label[for]:first").attr('for'));
});

$("[data-test]").click(function() {
   //console.log($(this).data('test')); 
   console.log($(this).nextAll("label[for]:first").attr('for'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="button" value="Test value"><br>
<label for="test1">Test Data</label>
<button data-test="test">test data</button>
<label for="test2">Test Data</label>

Upvotes: 0

gaganshera
gaganshera

Reputation: 2639

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>

Upvotes: 0

Related Questions