Simple JavaScript Query - javascript

I'm just beginning to learn Javascript and I'm currently trying to use it to change the HTML of an anchor tag. I'd rather not do this by each ID as I will eventually have a few of the same anchors so I wanted to do it with a class.
<div class="testing2">
Customize
</div>
<script type="text/javascript">
var test = document.getElementsByClassName('testing2');
var anchors = test.getElementsByTagName('a');
if (anchors[0]) {
anchors[0].innerHTML="Blank";
}
</script>
Problem is, I can make this work when using an id but not when using the class - I receive the error Uncaught TypeError: test.getElementsByTagName is not a function.
What am I missing?

You can simply use querySelector to achieve this as
document.querySelectorAll('.testing2 a')[0].innerHTML

The problem here is that test contains an array but you're not calling it as one.
var anchors = test[0].getElementsByTagName('a');

1st you need querySelectorAll('.testing2 a') to select all a element inside the element with class .testing2
2nd you need a forEach loop to loop through all the element selected and process to update innerHTML to Blank.
<div class="testing2">
Customize1
Customize2
Customize3
Customize4
</div>
<script type="text/javascript">
var testing2 = document.querySelectorAll('.testing2 a');
Array.prototype.forEach.call(testing2, function(el) {
el.innerHTML = "Blank";
});
</script>

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.

Javascript/Jquery Uncaught typeerror trying to replace html

trying to remove some text on my site using jQuery after the page has finished loading, and the code isn't working. When looking at the JS console in Chrome, I get the following error Uncaught TypeError: Cannot read property 'replace' of undefined.
Here's my code for replacing the text:
<script>
window.onload = function(){
var replaced = $("footer-copy").html().replace("'s Frontpage",'');
$("footer-copy").html(replaced);
};
</script>
And the HTML I'm trying to update:
<div class="footer-wrap">
<div class="footer-copy">© 2017 Andrew Gottschling's Frontpage Powered by Leafpub</div>
<div class="footer-design-author"><span>Design with</span> <i class="i-favorite heart"></i> by #leafpub</div>
</div>
Thanks for all the help in advance. :D
You need to add a class selector, otherwise jQuery searches for a tag with that name.
var replaced = $(".footer-copy").html().replace("'s Frontpage",'');
Notice the dot before the class name.
To find an element using class name, you need prepend this class with dot:
$(".footer-copy")
Try to use the class selector "." before the class name. Like this:
<script>
window.onload = function(){
var replaced = $(".footer-copy").html().replace("'s Frontpage",'');
$(".footer-copy").html(replaced);
};
</script>

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 movecontent from one div to another

I have the code that actually works:
<script type="text/javascript">//<![CDATA[
function MoveContent() {
var srcObj = document.getElementById("src");
var destObj = document.getElementById("dest");
destObj.value = srcObj.innerHTML;
}
//]]>
</script>
But I need to move content from 2 divs which isn't possible using this code.
I don't know JavaScript, so what should I add tho this code?
Sorry for bad English, thanks in advance
I suggest you use jQuery library. Have you heard of it?
http://jquery.com/
Simple code to accomplish your goal:
var srcHtml = $('#src').html();
$('#dest').html(srcHtml);
Use:
destObj.innerHTML = srcObj.innerHTML;
value is the value of an input element, innerHTML is the content of a DIV or other element.
Assuming Both are div's rewrite the following line
destObj.value = srcObj.innerHTML;
as
destObj.innerHTML= srcObj.innerHTML;
Since div is not having an attribute value you cannot copy the content to the destination div using value.
Like you get value from one div using
var srcObj = document.getElementById("src");
get another variable like srcObj2 and store the next div. Concatenate values of two variables and set it to the destObj

How to insert a button using classname tag in javascript?

i try to insert a button in gmail page.
it works fine using getElementsbyTagName() and appendchild().
But i want to insert the button in a classname like
i am also tried getElementsByClassName(),document.getElementsByClassName('abc')[0] and querySelectorAll().
i have got a
mainDiv value from <div id=:ab>
var mainDiv=document.getElementById(':ab');
var newDiv=document.createElement('div');
newDiv.setAttribute('id','innerdiv11');
var newButton=document.createElement('input');
newButton.type='button';
newButton.value='Encrypt';
newButton.id='btn11';
newDiv.appendChild(newButton);
//mainDiv.insertBefore(newDiv, mainDiv.lastChild);
mainDiv.appendChild(newDiv);
Now i need to get mainDiv value from <div class="abc"> value.
How can i achieve this?
i am using chrome browser.
Regards
Sanju
When you do sth like
var abc_array= document.getElementsByClassName("abc"); abc_array will have the array with the elements with "abc" class. You need to write a simple loop to find the value like...
var class_string =[];
for(var i=0;i<abc_array.length;i++){
class_string=class_string.push(abc_array.innerHTML);
}
//now you can return which class_string[0] or whatever you want.

Categories