Error when attempting to get all elements with specific Class [duplicate] - javascript

This question already has an answer here:
Parse a responseText to HTML in VBScript
(1 answer)
Closed 7 years ago.
I have an HTA in which I must update the innerHTML of a set of elements with the class driveLetter. Before I do this I must obviously grab an array of all elements with this class.
I've tried doing this with JS, however I'm told via an error that both of the methods below are not supported (Tested with IE9 and IE11). Using these functions within an HTML file works, but this is an HTA.
var driveLetterInstances = document.getElementsByClassName("driveLetter");
var driveLetterInstances = document.querySelectorAll(".driveLetter");
The errors generated by lines above -
Object doesn't support property or method 'getElementsByClassName'
Object doesn't support property or method 'querySelectorAll'
I don't specifically have to use JS and would be open to using VBS to carry out this function, but I have no clue on how to start with that (or even if it's possible).

To replace the innerHTML of set elements you could always just do something as simple as one line like this:
JQuery Solution 1:
// Find all the elements with the class name ".driveLetter" and replaces with "new content"
$(".driveLetter").html("new content");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- All elements with the same class name to be replaced with new content -->
<div class="driveLetter"> Hello </div>
<div class="driveLetter"> Hello </div>
<div class="driveLetter"> Hello </div>
<div class="driveLetter"> Hello </div>
JQuery Solution 2:
// Loop through the classname
$('.driveLetter').each(function(key, value) {
value.innerHTML = "New Content";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- All elements with the same class name to be replaced with new content -->
<div class="driveLetter"> Hello </div>
<div class="driveLetter"> Hello </div>
<div class="driveLetter"> Hello </div>
<div class="driveLetter"> Hello </div>
JQuery can be used by calling it from JQuery website or can be stored locally
Example from getting from online
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Example from getting from local file
<script src="js/jquery.min.js"></script>
Explanation of querySelectorAll()
I believe IE8 only supports querySelectorAll() in the standard mode. REF: Check this
The Selectors API is defined as part of the Selectors API
specification and is only available to Web pages displayed in IE8
standards mode.
Selectors API
The chances are that you're not setting the proper DOCTYPE declaration; you will need to add one.

Related

JavaScript span.appendChild() Returns Uncaught TypeError From Console [duplicate]

This question already has answers here:
Selecting element by data attribute with jQuery
(12 answers)
Closed 5 years ago.
I'm sort of a novice with HTML and JavaScript, but I'm running into some trouble with this one.
I have the following code snippet:
<div data-contents="true">
<div class="" data-block="true" data-editor="369vc" data-offset-key="e371k-0-0">
<div data-offset-key="e371k-0-0" class="_1mf _1mj">
<span data-offset-key="e371k-0-0">
<span data-text="true">TEXT HERE</span>
</span>
</div>
</div>
</div>
I'm trying to insert text where the "TEXT HERE" resides using the following commands (as found on this Stack Overflow thread) from within the console:
span = document.getElementById("data-text");
txt = document.createTextNode("TEXT HERE");
span.appendChild(txt);
However, when I run that command, all I get in return is Uncaught TypeError: Cannot read property 'appendChild' of null at <anonymous>:3:6.
I've read it's caused by the element not being defined prior to the script running, so it's unable to assign the text to it. I'm not fully clear on why it wouldn't run even though the website has already loaded though. Any ideas? I'm hoping to eventually hook this to a button that's loaded on the webpage, instead of it automatically running upon load if that makes sense.
NOTE: I'm not creating a website from scratch. This is a script being used on Facebook by TamperMonkey, so I can't permanently load it into the webpage.
You call this:
span = document.getElementById("data-text");
But don't have any id called data-text.
Either change the code to this:
span = document.querySelector("[data-text]");
Or change the html to this:
<span id="data-text" data-text="true">TEXT HERE</span>
Notice the id="data-text" That is what getElementById is looking for.

Storing object ID in HTML document: id vs data-id vs?

I would like to have an opinion on storing RESTful object IDs in document for accessing it later from JavaScript.
Theoretically speaking using id for addressing elements in HTML doesn't cut it anymore. Same element can be repeated twice on the page say in "Recent" and "Most Popular" queries which breaks the main point of using id.
HAML even has this nice syntax sugar:
%div[object]
becomes:
<div class="object" id="object_1">
But like I said, seems that it is not a good approach. So I am wondering what is the best way to store objects id in DOM?
Is this the current proper approach?
<div data-id="object_1">
An ID is intended to uniquely identify an element, so if you have a case where you want to identify two or more elements by some common identifier, you can use ID but it may not be the best option in your case.
You can use IDs like:
<div id="d0">Original Div</div>
<div id="d0-0">Copy of original div</div>
<div id="d1">Another original Div</div>
<div id="d1-0">Another copy of original div</div>
<div id="d1-1">Another copy of original div</div>
and get all the d1 elements using:
document.querySelectorAll('[id^=d1]');
or just d1 divs:
document.querySelectorAll('div[id^=d1]')
You could also use a class:
<div id="d0" class="d0">Original Div</div>
<div id="..." class="d0">Copy of original div</div>
<div id="d1" class="d1">Another original Div</div>
<div id="..." class="d1">Another copy of original div</div>
<div id="..." class="d1">Another copy of original div</div>
and:
document.querySelectorAll('.d1')
Or use data- attributes the same way. Whatever suits.
You can also have a kind of MVC architecture where an object stores element relationships through references based on ID or whatever. Just think outside the box a bit.
The purpose why data-selectors where introduces is because the users neednt want to use class or anyother attributes to store value.Kindly use data-selectors itself. In order to make it easy to access them use attributes selector i.e. [attribute='value']. PFB the fiddle for the same and also the example
jsfiddle
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-git2.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body onload="call()">
<div id="1" data-check='1'></div>
<div id="2" data-check='1'>sdf</div>
<div data-check='1'>sdf</div>
<div data-check='1'>sdf</div>
<div data-check='1'>sdf</div>
</body>
</html>
function call()
{
$("#1").html($('[data-check="1"]').length);
$("#2").html( document.querySelectorAll('[data-check="1"]').length);
}
Output: 5 5 sdf sdf sdf
#RobG is right by using 'class' you can get array of elements in JavaScript as-
var divs=document.getElelementsByClassName("className");
\\And you can loop through it(`divs[i]`).
AND according to #RobG and #Barmar data-* attribute is also a good option.
But here is some point(just point, not negative or positive, its totally depends on your application need) I want to discuss:
1] data-* element is HTML5's new attribute. Documentation
2] To retrieve elements in javascript, You need to use jQuery or more bit of JavaScript, coz all direct function available have specific browser support:
Like document.querySelector("CSS selector"); IE8+
document.getElementsByClassName("className"). IE9+
document.querySelectorAll("CSS selector"); etc.
So, basically for this point you need to choose according to your app need and browser compatibility.
3] Performance issue is also there on selecting by data-* attribute... Source
But, generally and if we go for latest application and selecting HTML5, data-* attribute + jQuery is a good option.
I was wondering about this too. Here's my POV using an example component.
CSS - styling across all buttons
Elements should not be referenced in JS using CSS classes because if you have multiple buttons that need to function differently, adding unique CSS classes for each component will get messy.
<div class="my-component">
JS - Grab the component when it can only appear once on a page
While browsers may handle multiple id okay, it would harm maintenance since this would be unexpected behavior from an id.
<div id="my-component">
const myComponent = document.querySelector('#my-component')
JS - Grab the component when it can appear multiple times on a page
ref or data-id could both work. ref has been popularized by React and Vue, so it may be more familiar to developers.
<div ref="my-component">
const myComponents = document.querySelectorAll('[ref="my-component"]')
or
<div data-id="my-component">
const myComponents = document.querySelectorAll('[data-id="my-component"]')

Extract all classes from body element of AJAX-ed page and replace current page's body classes

I am in the process of AJAX-ing a WordPress theme with a persistent music player. Wordpress uses dynamic classes on the <body> tag. The basic structure is as follows:
<html>
<head>
</head>
<body class="unique-class-1 unique-class-2 unique-class-3">
<div id="site-container">
<nav class="nav-primary">
Other Page 01
Other Page 02
</nav>
<div class="site-inner">
<p>Site Content Here</p>
</div>
</div>
<div id="music-player"></div>
</body>
</html>
I am currently successfully loading the content of /other-page-01/, /other-page-02/, etc, using load('/other-page-01/ #site-container'). However, I need to extract all <body> classes from the AJAX loaded page and replace the current page's <body> classes with them dynamically.
Note: Replacing the entire <body> element is not an option due to the persistent <div id="music-player">. I've tried jQuery.get(), but couldn't get it to work.
How do I extract the <body> classes from the AJAX requested page and replace the current page's <body> classes with them?
I am not very familiar with jQuery or Javascript, so the exact code would be extremely helpful. Any help is greatly appreciated.
Thanks,
Aaron
My typical solution would have been to tell you to throw the AJAX code in to a jQuery object and then read it out like normal:
$(ajaxResult).attr('class');
Interestingly though, it appears you can't do this with a <body> element.
I'd say the easiest solution (if you have control over the resulting HTML) is to just use some good ol' regex:
var matches = ajaxResult.match(/<body.*class=["']([^"']*)["'].*>/),
classes = matches && matches[1];
I say "if you have control over the resulting HTML", because this relies on the HTML being reasonably well formed.
The other method would involve parsing it as a DOMDocument and then extracting what you need, but this would take a lot more and is usually overkill in simple cases like this.
Convert the body within your returned html to a div with a specific ID, then target that id to get the classes of the body (which is now a div.)
modifiedAjaxResult = ajaxResult.replace(/<body/i,'<div id="re_body"')
.replace(/<\/body/i,'</div');
$(modifiedAjaxResult).filter("#re_body").attr("class");
Of course, if the body has an id, this will conflict with it, so an arbitrary data attribute might be less likely to break.
modifiedAjaxResult = ajaxResult.replace(/<body/i,'<div data-re-id="re_body"')
.replace(/<\/body/i,'</div');
$(modifiedAjaxResult).filter("[data-re-id=re_body]").attr("class");
http://jsfiddle.net/N68St/
Of course, to use this method, you'll have to switch to using $.get instead.
$.get("/other-page-01/",function(ajaxResult){
var modifiedAjaxResult = ajaxResult.replace(/<body/i,'<div data-re-id="re_body"')
.replace(/<\/body/i,'</div');
alert($(modifiedAjaxResult).filter("[data-re-id=re_body]").attr("class"));
// the following line replicates what `.load` was doing.
$(someElement).append( $("<div>").html(ajaxResult).find("#site-container") );
});

Unhandled Error: Cannot convert 'document.getElementById(punkte_liste_titel_user)' to object

I have a html page (partly generated with PHP), and I have a JavaScript file included at the bottom of the page that provides some onclick functions. I was struggling to get the variables from PHP to JS, so I created two <span>s with unique ids and put the content of the variables there (numeric/int values). My idea was to use var php_get_userid = document.getElementById(punkte_liste_titel_user).innerHTML; to have JS read the values into variables, and then use them.
However the getElementById doesn't work although the <span> with the corresponding ID definitly does exist. In Opera it says
Unhandled Error: Cannot convert
'document.getElementById(punkte_liste_titel_user)' to object
Chrome says
Uncaught TypeError: Cannot read property 'innerHTML' of null
The HTML of the area looks like this
<body>
<div id="wrapper">
<div id="punkte_liste_titel">
Points <span id="punkte_liste_titel_datum">20130901</span>/<span id="punkte_liste_titel_user">3</span>
</div> <!-- Ende Punkteliste -->
<div id="punkte_liste">
...
the JS starts like this
$('.punkte_kategorie_element').click(function() {
var php_get_userid = document.getElementById(punkte_liste_titel_user).innerHTML;
var php_get_datum = document.getElementById(punkte_liste_titel_datum).innerHTML;
...
the JavaScript file is included right before the </body> tag
I tried to create a minimal version of this at http://jsfiddle.net/WRfh5/2/ which doesn't run either... what am I missing?
you forgot to enclose id in quotes
getElementById
document.getElementById('punkte_liste_titel_user').
^ ^
jsfiddle

getElementsByClassName returns [] instead of asynchronous appended node

(I ask my question again after the first one was terribly formulated)
I face the following problem:
<div class="testA" id="test1"></div>
The above written element is predefined. I now load a xml tree via XMLHttpRequest & Co. delivering the following response:
<response>
<div class="colorSelector" id="0-0">
<div class="gbSelector" id="1-0">
<table style="none" id="2-0"></table>
</div>
</div>
</response>
I now append the first div using
request.responseXML.getElementsByTagName("response")[0]
.getElementsByTagName("div")[0]
into the predefined div
<div class="testA" id="test1">
The final document looks like this (checked using development tools):
<div class="testA" id="test1">
<div class="colorSelector" id="0-0">
<div class="gbSelector" id="1-0">
<table style="none" id="2-0"></table>
</div>
</div>
</div>
When I now try to get the element <div class="colorSelector" id="0-0"> using getElementById("0-0") I get the expected result.
But using getElementsByClassName("colorSelector") returns [].
Did I miss something? Is it probably a leftover of the fact the nodes were of type Element and not HTMLElement?
colorSelector is commented out. JavaScript only works within the DOM, and commented out portions aren't in the DOM.
Since you said that your getElementById("0-0") is successful, then clearly you don't actually have the nodes commented out.
I'm guessing you're doing:
document.getElementById("0-0").getElementsByClassName('colorSelector');
...which will not work because the element selected by ID does not have any descendants with that class.
Since you show HTML comments in the markup, I'd also wonder if you have some different element on the page with the ID "0-0". Take a look for that.
If your nodes are actually commented out, you'll need to first select the comment, and replace it with the markup contained inside:
var container = document.getElementById('test1'),
comment = container.firstChild;
while( comment && comment.nodeType !== 8 ) {
comment = comment.nextSibling;
}
if( comment ) {
container.innerHTML = comment.nodeValue;
}
...resulting in:
<div class="testA" id="test1">
<div class="colorSelector" id="0-0">
<div class="gbSelector" id="1-0">
<table style="none" id="2-0"></table>
</div>
</div>
</div>
...but there again, this doesn't seem likely since your getElementsById does work.
Here's a way to do it for Firefox, Opera, Chrome and Safari. Basically, you just do div.innerHTML = div.innerHTML to reinterpret its content as HTML, which will make that class attribute from the XML file be treated as an HTML class name.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<script>
window.addEventListener("DOMContentLoaded", function() {
var div = document.getElementsByTagName("div")[0];
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var doc = this.responseXML;
div.appendChild(document.importNode(doc.getElementsByTagName("response")[0].getElementsByTagName("div")[0], true));
div.innerHTML = div.innerHTML;
alert(document.getElementsByClassName("colorSelector").length);
}
};
req.open("GET", "div.xml");
req.send();
}, false);
</script>
</head>
<body>
<div class="testA"></div>
</body>
</html>
Remove the this.status === 200 if you're testing locally in browsers that support xhr locally.
The importNode() function doesn't seem to work in IE (9 for example). I get a vague "interface not supported" error.
You could also do it this way:
var doc = this.responseXML;
var markup = (new XMLSerializer()).serializeToString(doc.getElementsByTagName("response")[0].getElementsByTagName("div")[0]);
div.innerHTML = markup;
as long as the markup is HTML-friendly as far as end tags for empty elements are concerned.
<!--<div class="colorSelector" id="0-0">
<div class="gbSelector" id="1-0">
<table style="none" id="2-0"></table>
</div>
</div>-->
The above code is gray for a reason: it's a comment. Comments aren't parsed by the browser at all and have no influence on the page whatsoever.
You'll have to parse the HTML, read the comments, and make a new DOM object with the contents of the comment.
Please describe what you are doing with the returned results. There is a significant difference between a nodeList and a node, nodeLists are LIVE.
So if you assign a nodeList returned by getElementsByClassName() (or similar) to a variable, this variable will change when you remove the nodes inside the nodeList from the DOM.
I now append the first div
How do you do that? What you have in the responseXML are XML elements, and not HTML elements.
You shouldn't be able to appendChild them into a non-XHTML HTML document;
actually you shouldn't be able to appendChild them into another document at all, you're supposed to use importNode to get elements from one document to another, otherwise you should get WRONG_DOCUMENT_ERR;
even if you managed to insert them into an HTML due to browser laxness, they're still XML elements and are not semantically HTML elements. Consequently there is nothing special about the class attributes; just having that name doesn't make the attribute actually represent a class. getElementsByClassName won't return elements just because they have attributes with the name class; they have to be elements whose language definition associates the attributes with the concept of classness (which in general means HTML, XHTML or SVG).
(The same should be true of the id attributes; just having an attribute called id doesn't make it conceptually an ID. So getElementById shouldn't be working. There is a way to associate arbitrary XML attributes with ID-ness, which you don't get with class-ness, by using an <!ATTLIST declaration in the doctype. Not usually worth bothering with though. Also xml:id is a special case, in implementations that support XML ID.)
You could potentially make it work if you were using a native-XHTML page by putting suitable xmlns attributes on the content to make it actual-XHTML and not just arbitrary-XML, and then using importNode. But in general this isn't worth it; it tends to be simpler to return HTML markup strings (typically in JSON), or raw XML data from which the client-side script can construct the HTML elements itself.

Categories