Studento919 Studento919 - 2 months ago 31
Javascript Question

Jquery - Get attribute value of closest class

I am trying to grab the attribute value from the closest element with the class specified but keep getting back undefined.

Below is my HTML and my code, I am not too sure what am doing wrong to get back undefined.

HTML

<body>
<form action="/update" id="formwrite">
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title va-middle">Account Settings
<img src='../images/colopen.svg' data-swap='../images/coll.svg' class="panel-icon collapse-icon" role="button" data-toggle="collapse" data-parent="#accordion" href="#collaspeOne" aria-expanded="true" aria-controls="collaspeOne">
</h4>
</div>
<div id="collaspeOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
<div class="panel panel-default">
<div class="row fieldpos">
<fieldset class="form-group textwide">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" placeholder="Enter Email" required>
</fieldset>
</div>
</div>
</div>
</div>
</div>
<button type="submit" class="btn btn-success form-control savechanges">Save Changes</button>
<button class="btn btn-success form-control test">Call Function</button>
</form>
</body>


JS

$(document).on("click", ".test", function (){
$("input[required]").each(function(){
var inputval = $(this).val();
var collaspe = $(this).closest(".collapse-icon").attr("aria-expanded");
console.log(collaspe);
if(!inputval){
console.log("Required Empty");
$(".collapse-icon").trigger("click");
} else {
console.log("Required has value");;
}
});
});


Any suggestions?

EDIT: JSFiddle

Answer

$.closest traverses up the DOM searching only ancestors, it will not search for the "literal" closest element. Your .collapse-icon don't appear to be direct parents, but rather are children of the .panel-heading elements (which are parents). So the solution would be $(this).closest('.panel-heading').find('.collapse-icon')

UPDATE: I apologize, in my answer I mispoke. It should be .closest('.panel').find('.panel-heading .collapse-icon') since .panel-heading is a sibling of the or input's parent. So you need the .panel-body's parent and then find it's heading collapse icon.

Comments