How to get all element parents using jquery? i want to save these parents in a variable so i can use later as a selector.
such as <div><a><img id="myImg"/></a></div>
GetParents('myImg'); will return "div a" something like that
/// Get an array of all the elements parents:
allParents = $("#myElement").parents("*")
/// Get the nested selector through an element's parents:
function GetParents(id) {
var parents = $("#" + id).parents("*");
var selector = "";
for (var i = parents.length-1; i >= 0; i--) {
selector += parents[i].tagName + " ";
}
selector += "#" + id;
return selector;
}
GetParents('myImage') will return your nested selector: HTML BODY DIV A #myImage
Note sure why you'd want this but its reuseable as a selector.
You don't need to grab their selectors, as you can use them directly with jQuery afterwards.
If you want to use all parents later, you can do something like:
var parents = $("#element").parents();
for(var i = 0; i < parents.length; i++){
$(parents[i]).dosomething();
}
Every element has only one real parent. To access and save it, write the following:
myParent = $("#myElement").parent();
If you need the parents parents too, use .parents()
See documentation for further information:
http://docs.jquery.com/Traversing/parent#expr
http://docs.jquery.com/Traversing/parents#expr
You can use parents() to get your immediate parent, and their parents on up the tree. you can also pass a selector as an arg to only get parents that match a certain criteria. For instance:
$('#myelement').parents('[id$=container]')
to get all parents who have an id attribute whose value ends with the text "container"
You can get all the tags of an element's parents like this:
var sParents = $('#myImg').parents('*').map(function() {
return this.tagName;
}).get().join(' ');
you can also replace this.tagName with this.id for example or other attributes
Related
In my searches I have found plenty of questions/answers on how to find elements that end with a specific string. I've done a quick search and have not found anything specific about how to find elements that end with a variable. I did find this question/answer about how to use Javascript variables in jQuery selectors in general but I cannot get it to work and I wonder if it's because I'm trying to work against a set of elements I've already filtered down to.
Here are some id's of the elements I've already filtered:
["ms-goal-select-0", "ms-goal-input-0", "ms-goal-select-1", "ms-goal-input-1", "ms-goal-select-2", "ms-goal-input-2"]
And here is the (beginning of) the for loop I'd like to use to find and work with the select and input elements:
for (var x=0;;x++) { //will break when element(s) not found
selectEl = filteredElements.find('[id$="select-' + x + '"]');
inputEl = filteredElements.find('[id$="input-' + x + '"]');
....
But the above does not find the elements starting from the first iteration when x==0. What am I doing wrong?
Try using filter instead of find:
for (var x=0;;x++) { //will break when element(s) not found
selectEl = filteredElements.filter('[id$="select-' + x + '"]');
inputEl = filteredElements.filter('[id$="input-' + x + '"]');
....
Find only looks for matching children of the elements in filteredElements, whereas filter looks at the elements themselves.
jQuery's .find() only searches in descendants. I think you want to do a .filter() instead. I'd write this using the version of .filter() that takes a function and use a regular expression to match the elements you want:
var filteredElements = $("div");
var selectEl = filteredElements.filter(function() {
return this.id.match(/.-select-\d*$/);
});
var inputEl = filteredElements.filter(function() {
return this.id.match(/.-input-\d*$/);
});
console.log(selectEl.toArray());
console.log(inputEl.toArray());
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="ms-goal-select-0"></div>
<div id="ms-goal-input-0"></div>
<div id="ms-goal-select-1"></div>
<div id="ms-goal-input-1"></div>
<div id="ms-goal-select-2"></div>
<div id="ms-goal-input-2"></div>
I have a form that has multiple input, select, textarea elements. With jQuery, How can I get the name attribute values of each element? I have tried the following but its not working:
var names = $('[name]');
names.each(function(){
console.log(names.attr('name'));
})
You need to use this within the each() to refer to the element within the current iteration. Your current code is attempting to get the name of a set of elements which is logically incorrect. Try this:
var names = $('[name]');
names.each(function(){
console.log($(this).attr('name'));
})
You are still using names within your each function. Try this:
var names = $('[name]');
names.each(function(index, name){
console.log($(name).attr('name'));
})
This should loop around all the required elements and output the name and value to the console.
$('input,select,textarea').each(function() {
var thisname = $(this).attr('name');
var thisval = $(this).val();
console.log('name = ' + thisname);
console.log('value = ' + thisval);
});
You can try this way too.
var $name = $("[name]");
$name.get().map(function(elem,index){
console.log($(elem).attr("name"));
});
Add a class to all the elements you wish to get the names of.
Then you get all the elements from that class and iterate them to get their names.
formElements = $('.form-element');
for(key in formElements) {
name = formElements[key].attr('name');
// do what you wish with the element's name
}
P.S. You may need to wrap formElements[key] in $(), have not tested it.
// Selects elements that have the 'name' attribute, with any value.
var htmlElements = $("[name]");
$.each(htmlElements, function(index, htmlElement){
// this function is called for each html element wich has attribute 'name'
var $element = $(htmlElement);
// Get name attribute for input, select, textarea only
if ($element.is("input") ||
$element.is("select") ||
$element.is("textarea")) {
console.log($element.attr("name"));
}
});
Give your input ID then call attr() method
$("#id").attr("name");
I have an html div element, which contains lot of HTML-5 data- attributes to store extra
data with element. I know that we can use removeAttr of jquery to remove specific attribute,
but i want to know that is there any way to remove data- all atonce?
No, you have to loop through them and remove them individually. E.g.:
var $div = $("selector for the div"),
attrs = $div[0].attributes,
name,
index;
for (index = attrs.length - 1; index >= 0; --index) {
name = attrs[index].nodeName;
if (name.substring(0, 5) === "data-") {
$div.removeAttr(name);
}
}
Live copy | source
...or something along those lines.
Not aware of any wholesale way of doing this. You'd have to loop over the element's attributes with something like
var el = document.querySelector('p');
for (var i=0; i<el.attributes.length; i++)
if (/^data-/i.test(el.attributes[i].name))
el.removeAttribute(el.attributes[i].name);
I used $('#ul li').get() to get all the list elements and stored in an array, each of this list elements have classes...
var i;
var listClass = ('#ul li').get();
for(i=0;i<listClass.length;i++){
var theClass = listClass[i].attr("class"); //<--what's the proper function/method/code for this?
var content = listClass[i].innerHTML; //<-- works very well
//other codes here
}
How may i able to get the classes of each list elements...Thanks!
You can use jQuery's own map to do that:
alert($('#ul li').map(function() {
return this.className;
}).get());
http://jsfiddle.net/MhVU7/
for example. You can do anything with the returned array.
The reason the way you're doing it isn't working is because you're calling the non-existent method .attr on a native DOM element - it's not an extended jQuery object.
var lis = document.getElementById("ul").children;
for (var i = 0, len = lis.length; i < len; i++) {
var li = lis[i],
className = li.className,
value = li.value,
text = li.textContent;
// code
}
The get() method returns a native array of DOM elements, not a jQuery object.
You should use jQuery:
var lists = $('ul li');
var className = lists.eq(i).attr('class');
var content = lists.eq(i).text();
If you want to loop through all the elements
$('ul li').each(function(){
var className = $(this).attr('class');
var content = $(this).text();
});
I have commented the code to better help you understand it.
$("#ul li").each(function() { /* you should only be using # selector to identify id's - if it's all ul's you want just put ul. */
var klass = this.className; /* this refers to the native DOM object, which contains className */
var textContents = this.innerText || this.textContent; /* the text of the list, does not include html tags */
var childNodes = this.childNodes; /* the child nodes of the list, each unencased string of text will be converted into a TextNode */
console.log(klass + ' ' + textContents); /* replace console.log with alert if you do not have a console */
console.log(childNodes);
});
here is an example of the above.
Good Luck!
I working on something where I need two functions.
1 - I need to look at a group of children under the same parent and based on a class name, "active", add that element's ID to an array.
['foo-a','foo-b','foo-d']
2 - I then iterate through all the children in another parent and for each element I want to find out if it has any class name that match the ids in the array.
Does this element have class foo-a, foo-b or foo-d?
For the first part, I'd use map and get:
var activeGroups = $('#parent .active').map(function() {
return this.id;
}).get();
This gives you an array of id values (say, ['foo-a', 'foo-d']). You can then make a selector like .foo-a, .foo-b, .foo-c (the multiple selector) using join:
var activeSelector = '.' + activeGroups.join(', .');
This makes a valid jQuery selector string, e.g. '.foo-a, .foo-d'. You can then use this selector to find the elements you want using find:
var activeEls = $('#secondParent').find(activeSelector);
You can then do whatever you need to with activeEls.
var active = $("#foo").find(".active").map(function() {
return this.id;
}).get();
$("#anotherParent *").each(function() {
var that = this;
var classes = $(this).attr("class");
if(classes.indexOf(" ") !== -1) {
classes = classes.split(" ");
} else {
classes = [ classes ];
}
$.each(classes, function(i, val) {
if($.inArray(val, active)) {
// this element has one of 'em, do something with it
$(that).hide();
}
});
});
There's always .is('.foo-a, .foo-b, .foo-d'). Or if you actually just wanted to select them, instead of iterating and deciding for each element, $('.foo-a, .foo-b, .foo-d', startingPoint).