Error while selecting allElementsByID and adding a class to them - javascript

Hello I'm trying to add a class to all of my elements on a webpage. The overall goal is to grab all the elements on a webpage and add in a class. The class containing a font size will be changed to hide a message.
I'm getting this error
Uncaught TypeError: Cannot set property 'innerHTML' of null
I've tried moving my script outside the body tag of my index.html but its still not working.
Another problem is I can't add a class to all of the IDs I'm selecting. I can add classes manually like
$("#iconLog").addClass("style"); //this works
but when I try to add a class like this
empTwo = "#" + temp; //where empTwo is a string that equals "#iconLog"
$("empTwo").addClass("style") //this does not work
I'll post my entire script below for reference
$(function() {
var hideMsg = "f";
var n = hideMsg.length;
var i;
var j;
var holder;
var hideHolder;
// on button click - hide msg
$('#btnHide').on('click', function() {
//grab all IDS ON WEBPAGE
var allElements = document.getElementsByTagName("*");
var allIds = [];
for (var i = 0, n = allElements.length; i < n; ++i) {
var el = allElements[i];
if (el.id) {
allIds.push(el.id);
}
}
//ERRORS HAPPENING IN THIS LOOP
for(var i = 0; i < allElements.length; ++i)
{
console.log(allIds[i]);
try{
var temp = document.getElementById(allIds[i]).id;
}
catch(err){
document.getElementById("*").innerHTML = err.message;
}
tempTwo = "#" + temp;
console.log(tempTwo);
//$("#iconLog").addClass("style") //this works
$("tempTwo").addClass("style"); //this does not work
}
for(i = 0; i < n; i++) {
//set var holder to first value of the message to hide
holder = hideMsg.charCodeAt(i);
for(j = 7; -1 < j; j--) {
//set hideHolder to holders value
hideHolder = holder;
//mask hideHolder to grab the first bit to hide
hideHolder = hideHolder & (1<<j);
//grab the first element ID
if(hideHolder === 0) {
// embed the bit
// bitwise &=
} else {
//embed the bit
// bitwise ^=
}
}
}
});
});

To add a class to all elements you don't need a for loop. Try this:
$("*").addClass("style");
Same for setting the inner html of all elements. Try this:
$("*").html("Html here");

Remove the double quotes from empTwo .You don't need quotes when you are passing a varible as a selector. The variable itself contains a string so you don't need the quotes.
empTwo = "#" + temp;
$(empTwo).addClass("style") //this will work

Try this:
$(empTwo).addClass("style")
Note: You used string instead of variable:

well,
try this...
You were passing the varibale in the quotos because of that instead of getting value to empTwo it was searching directly for "empTwo".
$(empTwo).addClass("style");
to get all element try this-
var allElements = = document.body.getElementsByTagName("*");
Hoping this will help you :)

empTwo = "#" + temp; //where empTwo is a string that equals "#iconLog"
$("empTwo").addClass("style") //this does not work
You made mistake in the second Line.
The variable empTwo already is in string format.
So all you need to do is
$(empTwo).addClass("style") //this works because empTwo returns "#iconLog"

Related

JavaScript Search and Loop - doesn't return correct values

Please, can you check my code where is the error? It should loop trough 1 array to choose each string and then loop through second array and check, if the value from second string contains value of first string.
for (var i = 0; i < oldLines.length; i++){
var subStringEach = oldLines[i];
var subStringEachNoDash = subStringEach.replace(/[^a-z0-9]/g,'');
// read New URLs and line by line save them as an object
var newLines = $('#newUrl').val().split(/\n/);
var newUrlResult = [];
for (var j = 0; j < newLines.length; j++){
var newUrlString = newLines[j];
var newUrlStringNoDash = newUrlString.replace(/[^a-z0-9]/g,'');
var isThere = newUrlStringNoDash.search(subStringEachNoDash);
if (isThere !== -1 ) {
newUrlResult[i] = newLines[j];
}
else {
newUrlResult[i] = "";
}
}
stockData.push({OldURL:oldLines[i],SearchSubstring:subStringEach,NewURL:newUrlResult[i]});
}
Now it finds only part of the results.. I place to first array:
anica-apartment
casa-calamari-real
ostrovni-apartman
and to the second array:
http://tempweb3.datastack.cz/be-property/anica-apartment/
http://tempweb3.datastack.cz/be-property/ostrovni-apartman/
http://tempweb3.datastack.cz/be-property/st-michael-apartment/
http://tempweb3.datastack.cz/be-property/casa-calamari-real/
and it will only find and return casa-calamari-real, http://tempweb3.datastack.cz/be-property/casa-calamari-real/ and the others returns empty..
Any ideas please?
Here is the full code on Codepen: https://codepen.io/vlastapolach/pen/VWRRXX
Once you find a match you should exit the inner loop, otherwise the next iteration of that loop will clear again what you had matched.
Secondly, you should use push instead of accessing an index, as you don't know how many results you will have. And as a consequence you will need to relate the find string with it (because i will not be necessary the same in both arrays)
So replace:
if (isThere !== -1 ) {
newUrlResult[i] = newLines[j];
}
else {
newUrlResult[i] = "";
}
with this:
if (isThere !== -1 ) {
newUrlResult.push({
searchSubstring: subStringEach,
newURL: newUrlString
});
break; // exit loop
}
At the end, just output newUrlResult.
NB: If you want to leave the possibility that a search string matches with more than one URL, then you don't need the break. The push will then still prevent you from overwriting a previous result.
I see that you solved already) But maybe you will like this code too)
newUrlResult variable could be a string I guess, because loop breaks when one value is found. If no values where found there will be just empty string. And I'm not sure you need to call newLines = $('#newUrl').val().split(/\n/) on every iteration.
var stockData = [];
oldLines.map(function(oldLine){
var cleanOldLine = oldLine.replace(/[^a-z0-9]/g,''),
newLines = $('#newUrl').val().split(/\n/),
newUrlResult = '';
for (var j = 0; j < newLines.length; j++){
var newLine = newLines[j],
cleanNewLine = newLine.replace(/[^a-z0-9]/g,''),
ifExists = cleanNewLine.search(cleanOldLine);
if (ifExists !== -1) {
newUrlResult = newLine;
break;
}
}
stockData.push({OldURL:oldLine, SearchSubstring:cleanOldLine, NewURL:newUrlResult});
});

Javascript: Traversing through array and accessing its various elements?

Essentially what I'm trying to do right now is, given some input text, I split it up by white space and display on a
div id= "animation"
Every time a button is clicked, the array should go forward one word.
This is my current attempt.
function displayText() {
var displayText = document.getElementbyID("animation");
var list = (document.getElementbyID("input").split(/[ \tn]+/);
for (var i = 0; i < list.length; i++) {
displayText.innerHTML = list.get[i];
}
}
Is my thought process somewhat correct? For whatever reason, it doesn't seem to be working.
there are multiple issues in your method
function displayText() {
var displayTextAnimation = document.getElementbyID("animation"); //keep variable name and method name different
var list = (document.getElementbyID("input").value).split(/[ \tn]+/); //use value property and observe extra bracket
for (var i = 0; i < list.length; i++) {
displayTextAnimation.innerHTML = list.charAt(i); //observe replacing get by charAt
}
}

Javascript: assigning button id as a number inside of an innerhtml

I have this problem, where I can't seem to put the number of the "xq" into being the id for the buttons while using innerHTML.
Here's the code:
for (var xq = 0; xq < 3; xq++) {
var pass = xq;
tabletextvar = '<button id="buttontexto"; onclick="cancelObject(this.id);">Button</button>'
document.getElementById("buttontexto").innerHTML = pass;
}
document.getElementById("tabletext").innerHTML = tabletextvar;
Button ID ends up being "buttontexto" when I really want it to be what innerHTML. It could be that you can't have another innerHTML inside an innerHTML.
Any tips or fixes would be appreciated
If you want to have 3 buttons with id 1,2 and 3 then you need to append them, just using a variable inside the loop will override it and when the loop is over it will have the last value. You need to have a concatenated string.
var buttons = [];
for (var xq = 0; xq < 3; xq++) {
buttons.push('<button id="',xq,'" onclick="cancelObject(this.id);">',xq,"</button>")
}
document.getElementById("tabletext").innerHTML = buttons.join('');
Demo: Fiddle

innerText is undefined in Greasemonkey script

I've made code to query a document for matching strings and make a URL from the strings obtained. It looks through the tag elements looking for matches, makes the URL string, then it appends the link to the designated parentNode object. This code works fine in plain javascript, but it breaks when I stick it in Greasemonkey. I can't figure out why.
Here is a fully working version when I stick it in the chrome console:
//loop through elements by classname and find string matches
regexQueryEmail = "(AccountEmailAddress\\s)(.+?)(\\n)"
regexQueryContact = "(Contact with ID: )(.+?)(\\D)"
var Tags = document.getElementsByClassName('msg-body-div')
for (i = 0; i < Tags.length; i++) {
matchEmail = Tags[i].innerText.match(regexQueryEmail)
matchContact = Tags[i].innerText.match(regexQueryContact)
if (matchEmail != null) {
var emailString = matchEmail[2]
var placeHolder = Tags[i]
}
if (matchContact != null) {
var idString = matchContact[2]
}
}
var urlFirst = "https://cscentral.foo.com/gp/stores/www.foo.com/gp/communications/manager/main/191- 4559276-8054240?ie=UTF8&customerEmailAddress="
var urlSecond = "%3E&initialCommId="
var cscURL = urlFirst + emailString + urlSecond + idString
var cscLink = document.createElement('a')
cscLink.innerText = 'Communication History'
cscLink.href = cscURL
placeHolder.parentNode.appendChild(cscLink)
When I stick it in Greasemonkey, it gives me this error from the Greasemonkey "Edit" screen:
/*
Exception: Tags[i].innerText is undefined
#Scratchpad:18
*/
It has also told me that "placeHolder" is undefined, but I am unable to replicate this right now. I have a feeling that it has something to do with how the variables are scoped. I've added "var Tags;" and "var placeHolder;" to the top of the script and it didn't help.
Firefox uses the element.textContent property.
https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent?redirectlocale=en-US&redirectslug=DOM%2FNode.textContent
The variable placeholder in never declared in the scope you try to use it in. Instead it's declared somewhere in your for loop. Make sure you declare it within the same scope.
E.g.
var Tags = document.getElementsByClassName('msg-body-div')
var placeholder; // declare in same scope
for (var i = 0; i < Tags.length; i++) {
// lookup the tag once
var tag = Tags[i];
// get the text only once
var text = tag.textContent;
matchEmail = text.match(regexQueryEmail)
matchContact = text.match(regexQueryContact)
if (matchEmail != null) {
var emailString = matchEmail[2]
placeHolder = tag // deleted var statement
}
if (matchContact != null) {
var idString = matchContact[2]
}
}
...
// now you can use it.
if (placeHolder) {
placeHolder.parentNode.appendChild(cscLink);
}

function to change argument to another sign

I dynamically create this list element and information a user has typed in shows up in it when a button is clicked 'info' is text and shuld show as it is but 'grade' is a number that i want to convert to another sign with the function changeNumber() but I am new to javascript and cant figure out how to make this function, can anyone give a suggestion or point me in the right direction?
var list = $("#filmlista");
var list_array = new Array();
function updateFilmList()
{
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var listan = list_array[0][0];
var grade = list_array[0][1];
var element = '<li class="lista">' + list + '<span class="grade">'+ changeNumber(grade) +'</span></li>';
list.append(element);
}
should I use innerHTML? not shure I understand how it works? and how do I use the replace method if I have to replace many different numbers to the amount of signs the number is?
for example if the number is 5 it should show up as: *****, if number is 3 show up as: *** and so on
Here's some code that should do the trick:
Add this function into your script.
function changeNumber(number) {
var finalProduct = "";
for (var i = 0; i < number; i++) {
finalProduct += "*";
}
return finalProduct;
}
Replace the updateFilmsList with this code.
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var listan = list_array[0][0];
var grade = changeNumber(list_array[0][1]);
var element = '<li class="lista">' + list + '<span class="grade">'+ grade +'</span></li>';
list.append(element);
It looks like you're trying to do something like PHP's str_repeat. In that case, take a look at str_repeat from PHPJS
There are options other than a loop:
function charString(n, c) {
n = n? ++n : 0;
return new Array(n).join(c);
}
charString(3, '*'); // ***
You can use innerHTML to set the text content of an element provided none of the text might be mistaken for markup. Otherwise, set the textContent (W3C compliant) or innerText (IE proprietary but widely implemented) property as appropriate.

Categories

Resources