accessing to element id attribute value inside jquery.each - javascript

I'm selecting html elements
var elements = $('*[my-elem="false"]');
since each element has attribute id with some value I want inside iteration to get id of currently iterated element, so I tried
$.each(elements, function(index, item){
var itemId = item.attr("id").val();
});
but I'm getting following error
TypeError: item.attr is not a function

Try console.log(item). You should see that it's a regular HTML element -- not a jQuery object.
Note that .val() refers specifically to the value attribute of an element.
Both of those in mind, if your goal is to get the ID, you can use item.id, this.id, or $(item).attr("id").

.attr is a jQuery method, so you need to use your element as if it were a jQuery selector. Also, you don't need .val for .attr('id'), so this should work
var itemId = $(item).attr("id");

it is as simple as
var itemId = item.id;

item is a DOM element, attr is a jQuery function, so you just have to wrap it in the jQuery notation var itemId = $(item).attr('id').val();

You are using the wrong version of each when looping over DOM elements. Use this one. (https://api.jquery.com/each/)
elements.each(function(index){
var itemId = $(this).attr('id').val();
});

Try
var elements = $('selector');
elements.each(function() {
alert($(this).attr('id'));
});

var itemId = this.id;
will also work

Related

Quick Javascript thought about document.getElementByClassName for fixing error

Quick JS question :
if you do something like :
var text = document.getElementByClassName("grid3").innerText;
what is the best way if you have multiple elements with that class?
what is the best way if you have multiple elements with that class?
It depends which element you want to reference... your example will always fail because that method returns a NodeList regardless of the number of elements. Note that it's getElementsByClassName (plural "elements").
If you want to get the first:
var text = document.getElementsByClassName("grid3")[0].innerText;
If you want to get them all (in an array):
var allText = [].map.call(document.getElementsByClassName("grid3"), function (elem) {
return elem.innerText;
});
Its document.getElementsByClassName("grid3") with s...you will always get back an array of Objects. Therefore innerText will not work there.
You could get the innerText of single elements in this array like this:
var el = document.getElementsByClassName("grid3");
var text = el[0].innerText;
Or if you have just one element with that class, give it a id and use
var el = document.getElementById("yourelementsid");
Here is a fiddle that shows how it works and not works:
Fiddle
There is no method document.getElementByClassName, you lost "s".
document.getElementsByClassName always returns an array (or array-like object), so you have to loop througt this array to find what you want.
document.getElementByClassName() return a list of elements so you can use it as array.
var textArr = document.getElementByClassName("grid3");
for(var i = 0; i< textArr.length; i++){
// here is your text
var text = textArr[i].innerText;
}

Select all HTML ID's as a jQuery Object

Is it possible with jQuery to select all "IDS" of a specific block at the same time? I know that you can specify for example $('div') but I would like to select the ID's in my object. Is there an easy way to do this in jQuery? Something like:
$object = $('.wrapper');
$object.find(function(){
//GET ALL THE IDS..somehow?!
});
I'm a little curious of its purpose, but you could try this:
var ids = $('[id]', $object).map(function() {
return this.id;
});
It uses $object to provide the context for your selector, finds all elements within said context that have an id attribute, and then builds an array of the id values.
FYI, the resulting ids variable is a jQuery array-like object. If you just want a plain JS array, add a .get() after the map function:
var ids = $('[id]', $object).map(function() {
return this.id;
}).get();
// ^
jsFiddle Demo
$object.find('[id]').each(function(){
//this.id is your man
});

getElementsByTagName returning undefined

I have a function with one parameter which is an ID string:
function experimentOne(masterContainer) {
Which I call with:
experimentOne('#experimentOne');
I'm trying to get each div inside that given DIV and place it into an array, which works if I use:
var menuButtons = $('#myDivIDHere').getElementsByTagName('div');
However, if I use:
var menuButtons = masterContainer.getElementsByTagName('div');
I get this error in the console.
TypeError: 'undefined' is not a function (evaluating
'parentContainer.getElementsByTagName('div', masterContainer)')
If I output $(masterContainer); to the console it returns the correct element, and this code is working perfectly:
var experimentOneMenuButton = $(masterContainer).children().last();
So I'm stumped, any ideas?
Thanks.
You need to use jQuery element selector
var menuButtons = $('#myDivIDHere').find('div');
or
var menuButtons = $(masterContainer).find('div');
in your experimentOne() method
getElementsByTagName is a dom method, but $('#myDivIDHere') is a jQuery object where you don't have getElementsByTagName.
If you want to use getElementsByTagName, you need to use $(masterContainer)[0].getElementsByTagName where $(masterContainer)[0] gives you the dom reference.
I dont think the .getElementsByTagName is a method on the jQuery object.
You need to use
var menuButtons = $('#myDivIDHere').get(0).getElementsByTagName('div');
the .get(0) will return the DOM object, not the jQuery object

call a function with a specific index value of nodelist

Is it possible to call a function on specific index value of nodelist which is storing div like following :
var txtElem = txtdiv.getElementsByTagName("div");
the thing i want is that i am storing list of divisions in txtElem nodelist now i want to call a function on click event of the 3rd div stored in nodelist. The divisions are created dynamically and they don't have any id so they are not accessible by id.
from what you asked, it seems like this will do:
function toPseudoArray(nodeList) {
var ar = [];
for(var i in nodeList)
if(nodeList[i].nextSibling) // or for that case any other way to find if this is an element
ar.push(nodeList[i]);
return ar;
}
Pass your nodeList to this function, use what it returns as an array that contains your elements, and only your elements.
By the way, you could directly call function on a specific element simply using my_fab_function(txtElem[0]); -- of course, until you don't exceed the count.
The question is quite unclear. Seeing the jQuery tag, these come to my mind:
A way to call a jQuery function on a specified index using .eq():
var n = 1; //the index you need
$(txtElem).eq(n).css('color', 'red');
Simple Javascript to get the DOM element:
var n = 1; //the index you need
var elem = txtElem[n]; //elem will hold the DOM element
//call simple DOM methods on it:
var s = elem.innerHTML;
//you can also call jQuery functions on it:
$(elem).css('color', 'red');
By the way txtElem is not an object, it is a NodeList, an "array-like object".

how to use $.makeArray() with jQuery

Can anyone explain me how to do this, jquery's api is really lacking on this. What is wrong in the following code?
var arr = $(value).filter(function() { return $(this).is("TD"); } ).html();
alert(arr[1]);
I just want to grab the innerHTML/text of the td and put it in an array
Using .map() with .get() is one way to go:
var arr = $(value).map(function() {
var $th = $(this);
if($th.is("TD")) return $th.html();
}).get();
alert(arr);
I'm not sure what value represents, but if you change the selector to match only td elements, you could simplify the return statement with return $(this).html();.
.map() iterates over the elements, and adds the return value to the jQuery object. .get() retrieves just the array out of the jQuery object.
http://api.jquery.com/map/
http://api.jquery.com/get/
Sounds like value is a tr. Then you could do this:
var arr = $(value).children('td').map(function() {
return $(this).html();
}).get();
alert(arr);
To create an array with each item containing an array of that row's td element's html, you could do this:
var arr = [];
$('tr').each(function() {
arr.push($(this).children('td').map(function() {
return $(this).html();
}));
}).get();
console.log(arr);
This uses the standard .push() since I don't think that using .map() inside .map() would work. I think when you pass the inner array into the jQuery object, it just adds it to the main array (or something).
The html() function, and similar functions like text() and width() return a scalar value for the first matched element.
If you want an array with the HTML contents of every matched element, you should call map(), like this:
var arr = $(value).children('td').map(function() { return $(this).html(); }).get();
alert(arr[0]); //Alerts HTML of first <td> element
The .html() function:
Description: Get the HTML contents of
the first element in the set of
matched elements.
This is true of many jQuery functions that are retrieving values. So what's happening is that your filter function is returning a set of jQuery elements, but your .html() function is causing arr to just be assigned the html from the first element in the set.

Categories