Accessing Div, by class name, with javascript - javascript

I can not access this data within the div with javascript.
<div class="questions-text-alignment whiteTextWithShadow question-size-v4">
DATA HERE
</div>
Any suggestions?

Way 1
You can access the data using jQuery in the following way:
<script>
$(document).ready(function(){
var data = $(".questions-text-alignment").html();
alert(data);
})
</script>
Way 2
Without jQuery:
<script>
var data = document.getElementsByClassName("questions-text-alignment");
alert(data[0].innerHTML);
</script>

You can access using document.getElementsByClassName(), But the thing is you will get an array object. Using the array you have to find out yours. In the below sample I have assumed only one class available.
var arr = document.getElementsByClassName("question-size-v4");
alert(arr[0].innerHTML);
DEMO

You can try like this
<script>
function getHtml() {
var html = document.getElementsByClassName("questions-text-alignment")[0];
alert(html.innerHTML);
}
</script>
<div class="questions-text-alignment whiteTextWithShadow question-size-v4">
DATA HERE
</div>
<input type="button" name="click" value="click" onclick="getHtml()" />

You should Use Id to select element in this scenario -
DEMO
<script>
function changeData() {
document.getElementById('contentDiv').innerHTML= "Updated Content";
}
</script>
<body>
<div id="contentDiv">
Content Of My Div
</div> </br>
<input type = "button" onClick = "changeData()"
value = "change div text" />
</body>

#StevenTang I exactly got stuck on the same problem and here is my solution.
document.getElementsByClassName("question-size-4")
works fine on full HTML document load and only if you have a single DIV object identified by this class name.
Otherwise you get HTMLCollection object for preview via ChromeTools to be opened in your web browser.
To identify individual DIV object, including your Class name and Data Here use Firebug and select your Data and open in Firebug with right mouse click (submenu select).
Once your DIV object selected and identified to include your class name and your Data Here is opened in console.log (Chrome tools), clicking on HTMLCollection you get every DIV object identified by index (natural number) as in array.
Selecting the correct index (natural number), you can access your Data Here via
elements = document.getElementsByClassName("question-size-4");
DataHere = elements[correct DIV index].innerHTML or .innerText
You need to manipulate
x = elements.length;
first to know if any such DIV object identified by your class name really exists and has been downloaded.
If x = 0 it means HTMLCollection is empty and elements.innerHTML generates undefined string
If x = 1 there is exactly a single DIV identified by your class name, so
elements.innerHTML should work fine
If x > 1; you have got more DIV objects identified by your class name, so you needd to select the correct one from array data stracture, entering correct index, as above.
It took me months to study the problem and to find the correct answer.
thank you

Related

Document.querySelector returns a NULL value - script is at bottom of page

I am trying to get the patientNumber (ClinicA100-PF-TR1-P1) using querySelector. I keep getting a NULL value. The patientNumber is at the top of the page and the script is at the bottom. Even after the page is loaded, I click a button that runs the function and it still returns a NULL value.
Here is a screenshot of the selectors (https://recordit.co/IypXuuXib0)
<script type="text/javascript">
function getPatientNumber(){
var patientNumber = document.querySelector("patientNumber");
console.log(patientNumber);
console.log("hello");
return patientNumber;
}
var patientNumber = getPatientNumber();
console.log(patientNumber);
_kmq.push(['identify', patientNumber]);
</script>
Thank you for any help you can provide.
ADDITIONAL HTML INFORMATION:
I am using Caspio (database management software) to create this HTML code. I don't know if that may be the cause of the issue. Here is the HTML CODE.
<p class="sponsorName" id="sponsorNameID">[#authfield:User_List_Sponsor_Name]</p>
<p class="clinicNumber" id="clinicNumberID">[#authfield:User_List_Site_Number]</p>
<p class="protocolNumber" id="protocolNumberID">[#authfield:User_List_Protocol_Number]</p>
<p class="patientNumber" id="patientNumberID">[#authfield:User_List_Patient_Number]</p>
You are missing a dot.
var patientNumberNode = document.querySelector(".patientNumber");
var patientNumber = patientNumberNode.innerText;
if you select the item with class".", if you select with id, you should use"#".
var patientNumber = document.querySelector(".patientNumber"); // class select
var patientNumber = document.querySelector("#patientNumber"); // id select
Your selector is incorrect. It should be
var patientNumber = document.querySelector(".patientNumber");
Why is it failing:
When you use patientNumber as the selector, JavaScript looks for an element with a name of patientNumber. Since that's not the case, and you are looking for an element with a class of patientNumber, you need to use the . notation.
Addon Suggestion (can be ignored):
Since you are also using IDs, consider using document.getElementById() as it is faster than using document.querySelector().
Note that if you use document.getElementById(), your .patientNumber selector won't work. You need to write it as
document.getElementById('patientNumberID');
//ID based on the screenshot of the DOM you've shared
While the code is at the bottom of the page, and the element is at the top, it is not loaded asynchronously as it comes from a third party database. i put a delay in the getPatientNumber() and it works now.

Changing inner HTML of a button with dynamic id

On a project I'm working on, a HTML file is defining a Javascript template used on selection buttons. All buttons have a "Change..." label that I want to localize (set dynamically). In other cases I'm searching for the element ID and setting the InnerHTML accordingly. But in this case, the ID of the buttons are defined dynamically. Is it possible to have a text element inside the button element, search for this element, and set its InnerHTML value?
<script id="optionSelectionTemplate" type="text/x-handlebars-template">
<div class="sub-section option-selection">
{{#if name}}<h4>{{name}}</h4>{{/if}}
<div class="current"></div><button class="button" id="{{id}}" data-action-id="{{id}}">Change...</button>
</div>
</script>
I've been searching this for a while now. But given that my forte is not web development, I'm not really sure what to search for...
You may be able to get the button element(s) by its class instead; for example:
var x = document.getElementsByClassName("button");
As you suggested, you can improve your selection's precision by first getting the 'optionSelectionTemplate' element(s) like so:
var x = document.getElementById("optionSelectionTemplate").getElementsByClassName("button");
Or if you prefer:
var x = document.getElementById("optionSelectionTemplate").getElementsByTagName("button");
Here are some links for more on these method:
https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
https://www.w3schools.com/jsref/met_document_getelementsbytagname.asp
Depending on how dynamic your localization should become, you could also specify the text inside a (locale-dependent) CSS as in https://jsfiddle.net/1gws5kat/ :
[HTML]
<button class="button btn_change" id="{{id}}" data-action-id="{{id}}"></button>
[CSS]
.btn_change:before { content: "Change..."; }
In particular when dealing with a large number of identically-named elements (i.e. many "Change" buttons), this might be pretty handy.
You find those btns by this command:
var btnlist= $(':button')
This Camano get you all button in your html file, then loop ton in and apply your changing.
Before call this command, jquery must be install.

Changing class of html element using Javascript and string interpolation

I have a HTML element with the id of "bigOne". Its size is determined by its class and the associated CSS. The class names are "p1", "p2", "p3", etc, all the way up to "p100".
One the page is an input and a button. I am trying to create a function so that when a number is typed in the input and the button clicked that the class of the "bigOne" is changed to the corresponding number, e.g. when 80 is entered and the button clicked the class changed from "p50" to "p80". In my code below I have been able to create this exact scenario but what I want to be able to do is be able to type in any number and change the class appropriately, e.g. submitting 4 creates the class p4 or submitting 99 creates the class p99. This is where I have come completely stuck.
Im am sure there isn't too much code required but I just can not get it.
<div id="options">
<label></label>
<input id="changes" />
<button id="myButton">Submit</button>
</div>
<script type="text/javascript">
document.getElementById("myButton").onclick=function() {
if (document.getElementById("changes").value=="80") {
document.getElementById("bigOne").classList.contains('p50');
document.getElementById("bigOne").classList.toggle('p80');
}
}
</script>
Since you tag your question with jquery... :
<script>
$(function(){
$('#myButton').click(function(){
$('#bigOne').removeClass(); //to clean old classes
//we get the value from the input and add the p class
$('#bigOne').addClass('p'+$('#changes').val());
});
});
</script>
I suggest that you fetch the value of the element where the number is put in, and store it into the string below called "theNewClassName":
var theNewClassName = document.getElementById("elementToTakeValueFrom").innerHTML;
document.getElementById("elementToGiveClassTo").className = theNewClassName;
//or whatever classname you wanted it to change to
Or
document.getElementById("bigOne").className = "blablabla";
You get the idea.

Creating a div within an existing div in javascript issues

I have a problem, I wanted to create a div in html as a container and in javascript create new divs within the container based on a number input from a user prompt.
My html and javascript look like this.
HTML:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="stylesheet.css">
<title>Sketchpad</title>
</head>
<body>
<button type="button">Reset</button>
<div class= "container">
</div>
<script src="javascript.js"></script>
<script src="jQuery.js"></script>
</body>
JS
var row = prompt("Enter number of rows:");
var column = prompt("Enter number of columns:");
function createGrid(){
var cont = document.getElementsByClassName('container');
for(i=1; i<column; i++){
var sketchSquare = document.createElement('div');
cont.appendChild(sketchSquare);
}
}
createGrid(column);
I end up with this error: Uncaught TypeError: cont.appendChild is not a function.
I imagine this is something to do with the getElementsByClassName?
I do have a solution which involves creating the container div in javascript and appending the smaller squares inside the container div. I was just curious as to why my first soltuion didn't work?
cont[0].appendChild(myDiv) is a function.
When you document.getElements By Class Name as the name implies you are getting many elements (an array of sorts) of elements and this array don't have the same functions as each of its elements.
Like this:
var thinkers = [
{think: function(){console.log('thinking');}
];
thinkers don't have the method .think
but thinkers[0].think() will work.
try this: open your javascript console by right clicking and doing inspect element:
then type:
var blah = document.getElementsByClassName('show-votes');
blah[0].appendChild(document.createElement('div'));
It works!
also if you want to use jQuery which I do see you added...
you can do:
var cont = $('container');
cont.append('<div class="sketchSquare"></div>');
Try that out by doing this:
First get an environment that has jQuery.
Hmm maybe the jQuery docs have jQuery loaded!
They do: http://api.jquery.com/append/.
Open the console there and at the bottom where the console cursor is type:
$('.signature').append('<div style="background: pink; width: 300px; height: 300px"></div>');
You'll notice that you add pink boxes of about 300px^2 to 2 boxes each of which have the "signature" class.
By the way, prompt gives you a string so you'll have to do row = Number(row); or row = parseInt(row, 10); and another thing don't use that global i do for(var i = 0; ...
var cont = document.getElementsByClassName('container');
Because that^ doesn't return a node, it'll return an HTMLCollection.
https://www.w3.org/TR/2011/WD-html5-author-20110705/common-dom-interfaces.html#htmlcollection-0
You need to pick an individual node from that collection before appending.
There could be a couple of issues that could cause this. Without fully giving the answer here's what it could be at a high level.
Your script is ran before the DOM is fully loaded. Make sure that your script is ran after the DOM is present in the page. This can be accomplished using either the DOMReady event ($(document).ready equivalent without jQuery) or simply making sure your script tag is the last element before the closing body tag. (I usually prefer the former)
When you utilize document.getElementsByClassName('container') (https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName) this method returns an array therefore you would either need to apply the operation to all elements of the result or just select the zero-th as document.getElementsByClassName('container')[0]. As an alternative, if you would like to be more explicit you could also place an id on the container element instead to more explicitly state which element you would like to retrieve. Then, you would simply use document.getElementById([id]) (https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) and this would get back a single element not a collection.
The result of prompt is a string. Therefore you would have to first parse it as an integer with parseInt(result, 10) where 10 is simply the radix or more simply you want a number that is from 0-10.
You should include jquery library before your script, it`s important
<script src="jQuery.js"></script>
<script src="javascript.js"></script>

javascript grabbing span tag with both class and id

I have a span tag
<span class="vi-is1-prcp" id="v4-25">US $99.00</span>
I would like to grab it using pure javascript. JQuery or any other library is not allowed. Is that possible?
I recon that
getElementById('v4-25')
won't work since I have to specify class, too, correct?
Thank you,
So,
<div id="listprice">asdasdasdasdasd</div>
var string = document.getElementById('v4-25');
document.getElementById('listprice').innerHTML = string;
should print value of 'v4-25' in 'listpirce' ?
H
getElementById will work just fine. Just make sure you're running it after the page has loaded.
First of all, ids are unique. You can't have more than one. therefore, when you select element by id, you can only bring back one element (this is good).
Secondly, after you get an element, you have to do something with it. var string = document.getElementById('v4-25'); only gets you the element, but it looks like you want var string = document.getElementById('v4-25').innerHTML; for the price. If you do want the id instead you can do var string = document.getElementById('v4-25').id; but because that just returns "v4-25" it's a bit redundant.
There is no reason to add a class. Run the script after that dom element is loaded like this.
<span class="vi-is1-prcp" id="v4-25">US $99.00</span>
<script>
var elm = document.getElementById('v4-25');
</script>

Categories