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

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

Related

How to Loop through all nodeValues in DOM in JS

I am trying to loop through and increment the following:
var result_types = document.querySelectorAll('[data-title]')[0].attributes[2].nodeValue
specifically to grab and increment this value:
[0].attributes
Currently, I have the following:
var card = document.querySelectorAll('[data-title]')[0].attributes[2].nodeValue;
for (var i = 0; i < card.length; i++) {
console.log(card[i]);
}
I am trying to get this [0].attributes to increment to [1].attributes etc. when it is clicked
I am not sure what you are asking here, but if the issue is looping through the elements, this is happening because you get a NodeList back from querySelectorAll and not an array. Below will let you loop through node elements.
const nodes = document.querySelectorAll('.nodes');
[].forEach.call(nodes, (singleNode) => {
//Whatever you want.
})

Can I use a variable when setting element id trough javascript function?

I am learning javascript and i was wondering whether I can use a variable in this type of scenario.
I need a different id for each HTML element I create with the function in javascript. Would this work
<script>
var i=0;
function add()
{
i++;
var textbox = document.createElement("input");
textbook.setAttribute("type","text");
textbook.setAttribute("id",i);
}
</script>
As you can see, I am trying to set the id on the element with the i variable and i am not sure if I can do that.
Thanks.
Numbers should not be used as ID's for compatibilty reasons.
( What are valid values for the id attribute in HTML? )
Apart from the typo this should work.
You should also call your add function to see the effect.
var i=0;
var textboxAmount = 2;
function add()
{
i++;
var textbox = document.createElement("input");
textbox.setAttribute("type","text");
textbox.setAttribute("id",i);
document.body.appendChild(textbox);
}
for(var j = 0; j <= textboxAmount; j++){
add()
}
https://jsfiddle.net/bbx1Lfup/5/

Error while selecting allElementsByID and adding a class to them

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"

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 getelement where value contains specific string

I was wanting to count the occurrences of input fields that has a class name of text where that text input contains a specific value.
document.getElementById('c_files').getElementsByClassName('text').length;
So far this counts all textboxes with the class name of text but how can i make it value specific, say if i have 50 textboxes but i only want to count the ones where the value of that textbox contains abc somewhere within the string.
Thanks.
Edit: Thank you everyone for your time and answers, i have voted you all up, but i prefer John Bupit's solution out of them all so thats the one i will accept. Thanks again.
You can iterate over the elements and see which ones have the desired value:
var elems = document.getElementById('c_files').getElementsByClassName('text');
var count = 0;
for(var i = 0; i < elems.length; i++) {
if(elems[i].value.match(/abc/)) count++;
}
You can select all textboxes first and after that filter those matching your criteria. For example, by using Array.prototype.filter method:
var allText = document.getElementById('c_files').getElementsByClassName('text'),
filtered = [].filter.call(allText, function(textbox) {
return textbox.value.indexOf('abc') > -1;
});
Above code will produce and array of text elements where value contains substring "abc".
Hi I think you need to review this SO post-
https://stackoverflow.com/a/9558906/3748701
https://stackoverflow.com/a/10095064/3748701
This is something which would help in getting your solution.
You'll need to loop over all of the text boxes with the specified class and calculate it from there.
Something like the following logic should work:
var counter = 0;
var inputElements = document.getElementById('c_files').getElementsByClassName('text').length;
for (var i = 0; i < inputElements.length; i++) {
if (inputElements.value == "someText") {
counter++;
}
}

Categories

Resources