Reputation: 3557
<form class="register">
<div class="form-group">
<input type="submit" value="Signup" class="btn btn-submit" />
</div>
<div class="form-group needAccount" id="req_val">
<a href="#" class="toggleForms">Login from here</a>
</div>
</form>
Now I want to traverse this form and get all parents of last div#req_val
, so the output should be a string i.e.
form.register div.form-group.needAccount#req_val
Upvotes: 0
Views: 94
Reputation: 28437
You can use parents()
or .parentsUntil()
(if you need to stop at the form).
As .parents()
does not include the current element itself, you need to .add()
it to the resulting set. Then .map()
thru the set and create a string which you want for each element in the set. Use .get()
to get DOM elements out of the jQuery set and then .join()
them to a string.
In the below snippet I have included one more div
around the form
so that you know how .parents()
is traversing the tree.
Snippet:
var $parents = $("#req_val").parents().add("#req_val");
var str = $parents.map(function () {
var retVal = this.tagName;
retVal += this.id ? '#' + this.id : '';
retVal += this.className ? '.' + this.className.replace(' ', '.') : '';
return retVal;
}).get().join(' ');
$("#result").text(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<form class="register">
<div class="form-group">
<input type="submit" value="Signup" class="btn btn-submit" />
</div>
<div class="form-group needAccount" id="req_val"> <a href="#" class="toggleForms">Login from here</a>
</div>
</form>
</div>
<hr />
<p id="result"></p>
Upvotes: 1
Reputation: 66693
You can traverse through the parents using .parents()
and generate it yourself. See a sample implementation below:
// returns <tag-name>[.<class1>[.<class2>] ...][#<id>] for the passed element
function getSelector(_elem) {
var parts = [_elem.tagName].concat(_elem.className.split(/\s+/).map(function(_class) {
return (_class ? '.' + _class : '');
}));
_elem.id && parts.push('#' + _elem.id);
return parts.join('');
}
var elem = $('#req_val'), parents = elem.parents(), str = [];
parents.each(function() { // add parents
str.unshift(getSelector(this)); // unshift since parents() gives you the nearest parent first
});
str.push(getSelector($('#req_val')[0])); // add self
str = str.join(' '); // join with space
console.log(str);
Demo: http://jsfiddle.net/wu41vwuf/
Upvotes: 1