Reputation: 1665
I'm a bit stuck. I'd like to get the attribute value "for"
using a jquery selector. Though I am able to successfully log to the console, how can I get/log just the value for the attribute "for"
on the labels? I've tried console.log(labels['for'])
but that isn't the way to go. Below is the related code.
HTML:
<div class="inline-group" id="album_set-group">
<h2>Albums</h2>
<div class="inline-related">
<h3><b>Album:</b> <span class="inline_label">#1</span></h3>
<fieldset class="module aligned ">
<div class="form-row field-name">
<div>
<label for="id_album_set-0-name">Name:</label> <input id="id_album_set-0-name" maxlength="100" name="album_set-0-name" type="text">
</div>
</div>
<div class="form-row field-release_date">
<div class="date-field">
<label for="id_album_set-0-release_date">Release date:</label> <input id="id_album_set-0-release_date" name="album_set-0-release_date" type="text">
</div>
</div>
</fieldset>
</div>
</div>
JAVASCRIPT:
$(document).ready(function() {
var labels = $( "#album_set-group" ).find( "label" );
console.log(labels);
});
Upvotes: 0
Views: 54
Reputation: 4242
Please read http://api.jquery.com/attr/ for get attr
try this code:
$(document).ready(function() {
var labels = $("#album_set-group").find("label");
labels.each(function() {
console.log($(this).attr('for'));
});
});
Result: https://jsfiddle.net/cmedina/xo67uqc7/
Upvotes: 2
Reputation: 44098
Plain JavaScript:
<label>
s into a NodeList with querySelectorAll()
Array.prototype.slice.call()
getAttribute()
to get the for
attribute.push
each for
into a new array.console.log(newArray)
Snippet
var labelList = document.querySelectorAll('label');
var labelArray = Array.prototype.slice.call(labelList);
var total = labelList.length;
var forArray = [];
for (var i = 0; i < total; i++) {
var forAttr = labelArray[i].getAttribute('for');
forArray.push(forAttr);
}
console.log('for: ' + forArray);
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<div class="inline-group" id="album_set-group">
<h2>Albums</h2>
<div class="inline-related">
<h3><b>Album:</b> <span class="inline_label">#1</span></h3>
<fieldset class="module aligned ">
<div class="form-row field-name">
<div>
<label for="id_album_set-0-name">Name:</label>
<input id="id_album_set-0-name" maxlength="100" name="album_set-0-name" type="text">
</div>
</div>
<div class="form-row field-release_date">
<div class="date-field">
<label for="id_album_set-0-release_date">Release date:</label>
<input id="id_album_set-0-release_date" name="album_set-0-release_date" type="text">
</div>
</div>
</fieldset>
</div>
</div>
Upvotes: 1
Reputation: 487
You can use just the method .attr(). In your case you can do something like
$("#album_set-group").find("label").each(function() {
console.log($(this).attr('for'));
});
Upvotes: 1