Get and use all elements and attributes - javascript

I know you can get all the elements by a $("*") command using jQuery, but then suppose I wanted to traverse that list and pull a certain element from that list, how do I find that item? All I get from that is [object Object]. How do I look inside that object set?
Also, does the $("*") grab all of the attributes associated with each element? If not, how do I get those as well.
My purpose is this, if I modify some data using the "Inspect Element" thing in Chrome, I want to get all of the HTML of the page, after the modifications have been made, so as to essentially get a copy of the new HTML page.

I wanted to traverse that list and pull a certain element from that
list, how do I find that item? All I get from that is [object Object].
How do I look inside that object set?
You would use jQuery.each()
Also, does the $("*") grab all of the attributes associated with each
element?
Yes it does.
Example:
$("*").each(function(i, v){
// get tag name
console.log($(this).get(v).tagName); // or nodeName
// get node type
console.log($(this).get(v).nodeType);
// based on element type, you can get attributes using attr()/prop()
});

In the console you get sometimes [object Object]. To look inside the object set type:
console.dir($('*'));
Now you can 'open' the object in your console.
If you want to look for an element and your are not sure, if the element exists you can also:
if ($('#IDofTheElement').length > 0) { // Do something with it }

Related

Get first element from the selected group

With this $("div.modal-window.modal-progress a") selection I get two elements:
How to get the first selected object from the group and display it own property?
I tried this console.log($("div.modal-window.modal-progress a")[0].baseURI) but I get undefined.
Each of the selected in the set has baseURI:
And how one is able to iterate over all in the set?
$("div.modal-window.modal-progress a:first")
might just do it. Do post more of your code though so we can see the structure.
Use first() function of JQuery as
$("div.modal-window.modal-progress a").first()
Given a jQuery object that represents a set of DOM elements, the .first() method constructs a new jQuery object from the first element in that set.
$("div.modal-window.modal-progress a")[0] should get you the first item.
You get an undefined result because the property baseURI might not be defined in the first element.
If you want to get a jQuery object from the first selection, you can wrap the selected element by a $ like this:
$($("div.modal-window.modal-progress a")[0])
EDIT: After the OP changed his question:
You might want to use jQuery.each to iterate over all the elements that match your selector.
$("div.modal-window.modal-progress a").each(function() {
console.log($(this).prop("baseURI"));
});

querySelectorAll to find matching data-attribute

My app uses a Parse backend to keep a running list of all the concerts in my area that my friends and I are interested in.
On the main page I use a parse query display a module for each show stored in the database. As each module is created, I use this code to add a data attribute to the show's outermost div, corresponding to the show's object ID in parse:
var showId = object.id;
$("div.show_module:last").data("showId", showId);
I'm successfully able to retrieve the showId of a specific show when the user clicks on the show's module:
$("#showsList").delegate(".showModuleBody", "click", function() {
var storeObjectId = $(this).closest("div.show_module").data("showId");
});
That all works great, proving that assigning the data-attribute is working.
Where I'm running into trouble is trying to find an element with a specific data attribute or a specific value for that attribute on a given page. The end goal is to get the y-offset of that div so I can scroll the page to the appropriate spot. I assumed I could use the following code to find the element, but it isn't working -
// find all elements with class .show_module
var allShows = document.querySelectorAll('.show_module');
// find all elements with showId data attribute
var showsWithShowId = document.querySelectorAll('[data-showId]');
// find all elements with a specific showId data attribute
var showToFind = document.querySelectorAll("[data-showId='2']");
The first of those 3 works, proving that all the elements I'm interested in are loaded into the page by the time I'm calling this function, but the 2nd and 3rd queries return nothing.
Any idea what I'm doing wrong here? Is it something with syntax? Is querySelectorAll just incompatible with how I'm setting the data attribute?
I tried to include only what I figured are the salient bits of code, but if more is necessary please let me know.
Try This
$('*[data-customerID="22"]');
For more info, look here:
Selecting element by data attribute
jQuery's .data method does not create a HTML attribute, but associates a value in its internal data store with the element.
If you want to set a data attribute with jQuery, then you need to use:
$("div.show_module:last").attr("data-showId", showId);
To get the value, you can use .data('showId') or .attr('data-showId').
(note that HTML attributes are case-insensitive, so you can also write "data-showid" instead.)

Getting Hash and Storing in Variable

I'm trying to take the hashed value from an object. What I'm basically doing is this:
target = $('a[href^="#products"]');
targetHashed = target.hash;
$targetHashed = $(targetHashed);
console.log(targetHashed);
I'm putting the reference in "target", then getting the hashing and everything following it with ".hash" then converting the variable that contains the hashed value "targetHashed" to an object so I can do things like getting the offset, etc. Problem is that "targetHashed" is outputting undefined whenever I try to append .hash to it. Anyone know where I'm going wrong?
If you want to get the value of the href attribute of the selected elements you need to use attr so your second line would look something like.
targetHashed = target.attr('href');
But that only selects the first element, if you want to use all of them then you'll need to loop through that array.

Chrome console logging - Javascript

I'm wondering, why do some elements appear like an array and others like HTMLSpanElement. I've attached a picture as I'm not sure how to describe this otherwise.
The following log is made via
log(returner);
log(returner[0]);
Is returner a jQuery object as a result of $() ? $() will always return an array, even if there is one or zero elements inside of it. Without specifying an index in your first console.log, the entire contents of the array are outputted. In the second console.log, you include an array index, so only the element matching that index is outputted.
Because the element that appears like an array IS an array - it's an array of DOM element objects (HTMLSpanElement, etc).
When you log the first element of the array with returner[0], that element is a DOM object, so it logs it as an object.
Because (it looks like) returner is not an element, but an array of elements.

append object to innerHTML and get that object from innerHTML

here is an example in jsfiddle.
I want to know if I can append a javascript object to innerHTML, that get that object again from innerHTML as object.
something like,
alert((this.innerHTML).html);
that's just an example, don't ask me why do you need this?
I'm trying to edit an existing code, and I have to do this so.
I have to transfer an object via div.innerHTML.
Check this jsfiddle. In it, I add the object to the div as a 'data-'-attribute, using JSON to convert it to a string. After that, adding some comment to the div triggers the DOMSubtreeModified-handler, in which the 'html'-part of the object is retrieved and alerted. It that something to work with?
In this case, quite possible your only option is to convert your object to string and then put that into the element. (This is done by looping through the key, values building the string as you go.)
You would reverse the process to convert it back into an obj.
I know some javascript libary's have helper functions to make this process very simple.
You could try adding the data directly onto the dom element, rather than as its content..
tempDiv.objData = myObject;
It was suggested to use JSON, but no code. So:
function addObjAsJSON(el, obj) {
el.setAttribute('data-myJSON', encodeURIComponent(JSON.stringify(obj)));
}
function getObjAsJSON(el) {
return JSON.parse(decodeURIComponent(el.getAttribute('data-myJSON')));
}
That should allow you to add anything as a serialised object, then get it back. You should add some error checking to make it robust though (e.g. check that you get a string back from the call to getAttribute).
For user agents that don't have built-in JSON support, see json.org which has a link in the javascript section to json.js.

Categories

Resources