I'm fairly new to JavaScript and I'm practicing with smaller projects.
What I want to do is change the inner HTML of a bunch of tags to the number in which they are in order.
Let me explain.
I want to go from this.
*Number <br>
*Number <br>
*Number
To This.
*1 <br>
*2 <br>
*3
Doing it purely from JavaScript.
This is what I have right now.
HTML
<p id="thisIsANumber">Number</p>
<p id="thisIsANumber">Number</p>
<p id="thisIsANumber">Number</p>
<button onclick="orderElements()">Order Elements</button>
JavaScript
function orderElements() {
var reference = document.getElementById('thisIsANumber');
for (var i = 0; i < 3; i++) {
reference[i].innerHTML = i;
}
}
As mentioned in comments you can't have multiple things that use the same id — you should use a class instead.
For example, this says you have a paragraph, and this kind of paragraph is a "numbered-paragraph":
<p class="numbered-paragraph">
Now you can select all of the paragraphs that have that class, loop over them and give each a number.
This example code is explicit so it's clear — there are many ways this could be shortened:
document.getElementById('numberGenerator')
.addEventListener('click', function(e) {
const paragraphs = document.querySelectorAll('.numbered-paragraph');
let i = 1;
for (p of paragraphs) {
p.innerText = 'paragraph number ' + (i++);
}
});
<p class="numbered-paragraph">Number</p>
<p class="numbered-paragraph">Number</p>
<p class="numbered-paragraph">Number</p>
<button id="numberGenerator">Order Elements</button>
Note I've also used addEventListener with an anonymous function instead of an inline onclick= with a named function.
The main issue here is that you used an id instead of class. The problem with this is that an id is used to identify one element, whereas a class can be used to identify several. If what you want is numbered paragraph elements, and not an ordered list, this should do the trick:
function orderElements() {
var reference = document.getElementsByClassName("thisIsANumber");
for (var i = 0; i < 3; i++) {
reference[i].innerHTML = i;
}
}
<body>
<p class="thisIsANumber">Number</p>
<p class="thisIsANumber">Number</p>
<p class="thisIsANumber">Number</p>
<button onclick="orderElements()">Order Elements</button>
</body>
I was trying to append some dynamically created html. It throws an error while using getElementById. .audit-table-element is a div in DOM with that particular class.
<div class="audit-table-element"></div>
Javascript :
var elems = document.getElementsByClassName('audit-table-element');
for(var i = 0; i < elems.length; i++) {
elems[i].getElementById("always-audit-table" + category.id + "")
.getElementsByTagName("tbody")[0]
.insertAdjacentHTML("beforeend", auditTableRow);
}
Error - TypeError: elems[i].getElementById is not a function
When I remove the line getElementById("always-audit-table" + category.id + ""), appending is working, but gets appended at the wrong place. So i need to have that line for the HTML to be appended at the right place
You can use querySelector instead of getElementById. Your code should be like below.
elems[i].querySelector("[id = always-audit-table" + category.id + "]")
.getElementsByTagName("tbody")[0]
.insertAdjacentHTML("beforeend", auditTableRow);
querySelector : These are used to select HTML elements based on their id, classes, types, attributes, values of attributes, etc.
Click here to learn more about querySelector
I don't know how your code looks like, but i try to create one example here. have a look to this, your doubts will be cleared out
var testRow = "<tr><td>Data 1</td><td>Data 2</td></tr>";
var ele = document.getElementsByClassName('test');
for(var i = 0; i < ele.length; i++){ debugger;
ele[i].querySelector("[id = id"+i+"]").getElementsByTagName("tbody")[0].insertAdjacentHTML("beforeend", testRow);
}
<div class='test'>
<div id='id0'>
<table><tbody></tbody></table>
</div>
</div>
<div class='test'>
<div id='id1'>
<table><tbody></tbody></table>
</div>
</div>
I am working on a website where I dont have any control on the code (functionality side. however even if I had the access I wouldn't be able to make any changes as I am a front end designer not a coder..lol). The only changes I can make is CSS, js.
What I am tring to do:
I got the url on the page like this:
www.test.com/#box1#box3#box5
(I am not sure if I can have more than one ID in a row. please advice. However thats how the developer has done it and I dont mind as there are no issues yet)
the page html
<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
<div id="box4"></div>
<div id="box5"></div>
I would like to take different ids from the URl and use it to hidhlight the divs with that ID (by addding a class name "highlight")
The result should be like this:
<div id="box1 highlight"></div>
<div id="box2"></div>
<div id="box3 highlight"></div>
<div id="box4"></div>
<div id="box5 highlight"></div>
I would like to learn the smart way of taking just the id numbers from the url and use it to select the div with that paticulat no.
just a quick explanation:
var GetID = (get the id from the URL)
$('#box' + GetID).addClass('highlight');
Try This...
var hashes =location.hash.split('#');
hashes.reverse().pop();
$.each(hashes , function (i, id) {
$('#'+id).addClass('highlight');
});
Working fiddle here
var ids = window.location.hash.split('#').join(',#').slice(1);
jQuery(ids).addClass('highlight');
or in plain JS:
var divs = document.querySelectorAll(ids);
[].forEach.call(divs, function(div) {
div.className = 'highlight';
});
There are various way to resolve this issue in JavaScript. Best is to use "split()" method and get an array of hash(es).
var substr = ['box1','box2']
// Plain JavaScript
for (var i = 0; i < substr.length; ++i) {
document.getElementById(substr[i]).className = "highlight"
}
//For Each
substr.forEach(function(item) {
$('#' + item).addClass('highlight')
});
//Generic loop:
for (var i = 0; i < substr.length; ++i) {
$('#' + substr[i]).addClass('highlight')
}
Fiddle - http://jsfiddle.net/ylokesh/vjk7wvxq/
Updated Fiddle with provided markup and added plain javascript solution as well -
http://jsfiddle.net/ylokesh/vjk7wvxq/1/
var x = location.hash;
var hashes = x.split('#');
for(var i=0; i< hashes.length; i++){
var GetID = hashes[i];
//with jQuery
$('#box' + GetID).addClass('highlight');
//with Javascript
document.getElementById('box' + GetID).className = document.getElementById('box' + GetID).className + ' highlight';
}
<html>
<body>
<script type="text/javascript">
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
</script>
<table>
<tr>
<td><input type = 'button' value = "key[0][1]" /></td>;
</tr>
</table>
</body>
</html>
This is a small example above, but I'm basically making an onscreen keyboard and I already have the loop which positions the buttons, however in my loop I try to assign the value of each key similarly to the code above, but instead of printing q w e r t y for each key, it prints key[row][col] for each button. How do I get the letters to appear on the button using a similar method to the above?
The below code generates the keyboard kind of layout that you are expecting:
<html>
<head>
<script type="text/javascript">
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
</script>
<body>
<script type="text/javascript">
for(var i = 0; i < key.length; i++)
{
document.write("<div>");
for(var j = 0; j < key[i].length; j++)
{
document.write("<input type='button' value='" + key[i][j] + "'/>");
}
document.write("</div>");
}
</script>
</body>
</html>
The only thing the second and third row should move right a little bit to look like real keyboard. For this we can do padding for the div tags. Hope this helps you.
Something like this?
HTML:
<input id="myInput" type="button" />
JavaScript:
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
var input = document.getElementById('myInput');
input.value = key[0][1];
That's the basic idea. You already have a loop to work with. The javascript should be after the HTML on the page. Your elements need to exist before you can grab them. Not sure if this is your precise confusion, though.
You can use javascript to create the elements, but unless there's a reason to do so, you might as well write HTML. If you're using a javascript function to generate the elements as well as fill their values in, you'll need javascript's document.createElement:
var keysArr = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
var generateKeys = function(keys) {
for (var i = 0 ; i < keys.length ; i++) {
for (var j = 0 ; j < keys[i].length ; j++) {
var input = document.createElement('input');
input.value = key[i][j];
document.appendChild(input); // or put it wherever you need to.
}
}
}
generateKeys(keysArr);
Wrapping it in a function will also allow you to re-use the code with different keyboard layouts if you wanted to, say, let the user choose a different layout on the fly.
You will need to set them programmatically, rather than in the value attribute.
You will also need to create the tr/td/input elements within your loop programmatically, for example:
http://www.dustindiaz.com/add-and-remove-html-elements-dynamically-with-javascript/
When you create the input tag programmatically, you can set the value attribute using javascript - eg.
newInput.setAttribute("value", key[rowIndex, cellindex]);
can anyone give me the javascipt code to extract following instances of sf_number from my HTML?
<ul class="multi_value_field" style="width: 99.5%;">
<li class="choice" choice_id="sf_number">sf_number<a class="close">×</a><input type="hidden" name="ticket[set_tags][]" value="sf_number" style="display: none;"></li>
<li class="search_field_item"><input type="text" autocomplete="off" tabindex="20"></li>
</ul>
Basically I want to replace all three instances of sf_number with a different
value from another field. This is the code I have made to try and extract sf_number but doesn't work so far:
var n2 = document.getElementsByClassName("multi_value_field").getElementsByClassName("choice");
Thanks in advance
UPDATE
How can I change my existing code by using your suggestions below?
<html>
<script type="text/javascript">
copy = function()
{
var n1 = document.getElementById("ticket_fields_20323656");
var n2 = document.getElementById("choice").getElementsByClassName("sf_number")[0] ;
n2.value = n1.value;
}
</script>
<input type="button" value="copy" onClick="copy();" />
</html>
Update
This doesn't seem to work, is it correct?
<html>
<script type="text/javascript">
copy = function()
{
var fields = document.getElementsByClassName("multi_value_field")[0].getElementsByClassName("choice");
for (var i = 0; i < fields.length; i++)
fields[i].setAttribute("choice_id", "document.getElementById("ticket_fields_20323656").value");
fields[i].getElementsByTagName("input")[0].value = "document.getElementById("ticket_fields_20323656").value";
fields[i].firstChild.nodeValue = "document.getElementById("ticket_fields_20323656").value";
}
</script>
<input type="button" value="copy" onClick="copy();" />
</html>
Try this code. Do you also want to replace the text?
<script>
var fields = document.getElementsByClassName("multi_value_field")[0].getElementsByClassName("choice");
for (var i = 0; i < fields.length; i++)
{
fields[i].setAttribute("choice_id", "something else");
fields[i].getElementsByTagName("input")[0].value = "something else";
fields[i].firstChild.nodeValue = "something else";
}
</script>
var n2 = document.getElementsByClassName("multi_value_field") returns a node List
So you need to use a for loop to iterate the list..
var n2 = document.getElementsByClassName("multi_value_field");
for(var i =0;i< n2.length;i++){
var $li = n2[i].getElementsByClassName("choice"); This is again a Node list.
for(var j = 0;j< $li.length ; j++){
$li[j] // This the li in question
}
}
UPDATE
var n1 = document.getElementById("ticket_fields_20323656");
var n2 = document.getElementById("choice").getElementsByClassName("sf_number");
// The above line again return's node List ....
n2.value = n1.value;
Replace that by this line with this if you feel it has a single class
var n2 = document.getElementById("choice").getElementsByClassName("sf_number")[0] ;
But the thing is I don't see the element with id="choice" in the HTML.
I'm not sure I understand your question.
There is no HTML attribute named "choice_id", and using non–standard attributes is not a good idea. If you want to identify a number of elements using the value 'sf_number', you should use a class instead, e.g.
<li class="choice sf_number">sf_number<a class="close">×</a>...</li>
Now you can get all elements with class of "sf_number" using getElementsByClassName, or querySelectorAll. You can add a shim for one or both of those to make life easier, then use:
var sfNumbers = document.querySelectorAll('.sf_number');
Then you can iterate over the collection per other answers.
An element can have multiple classes, the above will select only those with a class of 'sf_number'. If you want to select the text sf_number, you are much better off putting it in a span or similar element so you can reference it more directly. Relying on different browsers to insert text nodes consistently is not a good idea.