JavaScript: assign unique ID to elements containing a certain class - javascript

So I have this HTML code:
<p style="margin-bottom: 5px"><span id="" class="stars-container stars-custom">★★★★★</span></p>
basically I want to assign a unique id to each instance of this element, so first element id="1", second element id="2" etc.
I was thinking of using getElementsByClassName to identify them and grab the class name, but how do I assign and a unique id?? I'm pretty new to JS so I don't get how the loop will look like.

This will handle. You basically select all of the p elements with the classes you indicate, loop over them and set the id for each of them to the index of the loop variable.
I could not use a foreach loop as it's not usable on HTMLCollections
const paragraphs = document.getElementsByClassName('stars-container stars-custom');
for (let i = 0; i < paragraphs.length; i++) paragraphs[i].setAttribute('id', i + 1);

Related

jQuery select a specific element of an element class with variable as the selector

I want to add a class to a specific element of an element array, but I want to add it based on a variable of the for loop, not just a random number, and add it to more than one elements if I have to, but the point is, I need to search the elements with the variable given to me!
for(var a = 0; a < array.length; a++){
$('.results').append('some html divs here');
if(array[a].id == $.cookie('userId')){
$('.buyButton').addClass('disabled'); // here's my problem I don't want to add the
//disabled class to every element with the buyButton class, but just the one selected by the if statement
}
}
Thank you!
It looks like your array is an array of divs, if so you can use your array rather then the class as your jQuery object to alter the class, as so
for(var a = 0; a < array.length; a++){
$('.results').append('some html divs here');
if(array[a].id == $.cookie('userId')){
array[a].addClass('disabled');
}
}

Getting a Javascript function to apply to all Elements by ID

I have as simple webpage where dates and names are input into form fields and fields and transmitted in context in paragraphs when the user clicks a button. Some are output to spans, using InnerHTML others to inputs.
Some dates/names must appear multiple time in the document. I need to my code to apply to apply to all boxes with that actual ID. Should I instead be using a class?
Example this outputs a date:
// This Defines the Date the Medical Was received
var MEDRName = document.getElementById("MEDRName");
var elements = document.getElementsById("OUTMEDR");
for(var i = 0, len = elements.length; i < len; i++){
elements[i].onclick = function () {
var OUTMEDR = document.getElementById("OUTMEDR");
var name = MEDRName.value;
This appears in multiple paragraphs, and I need each element with this ID to populate.
<p> The medical was signed by <input type="text" id="MEDRNAME" /> </p>
<p><input type="text" id="MEDRNAME" /> indicated that yadayadayada</p>
I need to my code to apply to apply to all boxes with that actual ID
Id should be unique. Since there should be only one element with an id, getElementsById isn't valid, but getElementById is.
You can see more info here.
Should I instead be using a class?
Yes, you should and it's the appropriate way to do it. And then you can use getElementsByClassName or querySelectorAll to select them.

Applying class change to all getElementsByTagName - Pure JavaScript

I want to use JavaScript only, not jQuery.
I have 2 problems, firstly I want to correctly apply/remove a class attribute to each li element within a ul
Ideally when one li element has a class set, the remaining do not have a class attribute set(remove if set) - however from my testing when I need to unset/remove a class from elements I have only been able to set the class like class="", which works but isn't ideal.
I have been able to get scrape child elements id's of a ul with getElementsByTagName
<ul id="u">
<li id='car' class="t">1</li>
<li id='blue'>2</li>
<li id='eight'>3</li>
<li id='nasa'>4</li>
</ul>
var u = document.getElementById('u');
var li = u.getElementsByTagName('li');
My second problem is looping over li seems to give me alot of excessive rubbish.
for (var i in li) {
alert(li[i]["id"]);
}
//returns
car
blue
eight
nasa
undefined
undefined
undefined
What would be the best way to do this?
Because that's how you iterate over an object, not an array.
The standard for loop will return only the results you expected:
for (var i = 0; i < li.length; i++) {
alert(li[i]["id"]);
}
To remove all the classes from them, use this inside the loop:
li[i].className = "";
To remove just a specific class:
li[i].classList.remove("classNameHere");
If you want to remove the whole element attribute (not just reset classes), use:
li[i].removeAttribute("class");
See all three examples in action here: http://jsfiddle.net/vr9mm2vk/1/
Use a standard for loop (instead of a for in loop) so you only hit the numeric properties.
for (var i = 0; i < li.length; i++)
Currently you are hitting all the properties including, for example, li['length'].

Add a target attribute with a loop

I have an input button where is written within a blade foreach loop in a laravel project.
<div class="v-percentage">
<input id="copycode" type="Submit" value="Embed">
</div>
I am trying to write a script that will allow me to add a target attribute on the input so each button would be unique, and do something like this answer here. The script I wrote so far it should get the element and then within a for loop to add the target which i am not sure yet how I should do this.
var elements = document.getElementById('#copycode');
alert(elements);
for(var i = 0; i < elements.length; i++)
{
//add the target to the element
}
Also, when I alert the elements is returning null. How can i work that out?
document.getElementById('copycode')
getElementById just wants the ID, not a CSS selector.
Also, this will return one element (not a NodeList). IDs are unique throughout the page. If you want to select multiple elements, use classes and getElementsByClassName.
the Javascript function getElementById only returns one element. If you are trying to get a set of elements, try to use a class
<input class="copycode" type="submit" value="Embed" />
Then you could use a jquery selector to get the set of elements and iterate over then
$(".copycode").each(function(key, element){
element.attr("target", "foo");
});
If you don't want to use jquery, use the javascript function getElementsByClassName and a for to iterate over the set of elements
var elements = document.getElementsByClassName("copycode");
for (var i = 0; i < elements.length; i++) {
elements[i].setAttribute("target", "foo");
}
You can't have more than one ID with the same name, ID should be unique per page.
The getElementById() method accesses the first element with the specified id.
If you want get all the input element then you should try getElementsByTagName()
The getElementsByTagName() method accesses all elements with the specified tagname.
document.getElementsByTagName("input");
var elements = document.getElementsByTagName("input");
alert(elements);
for(var i = 0; i < elements.length; i++)
{
//add the target to the element
}
Hope this helps!

remove div without an id tag

I need a solution to remove a div without an ID tag in JavaScript only. The div looks like this <div align="center">.
Here is the full structure.
<tr id="-1">
<td class="stxt">
<div align="center">
</div>
</td>
</tr>
You need to work out how to get a reference to it, once you've done that, you can remove it using:
div.parentNode.removeChild(div);
Of course the align attribute has been deprecated, but anyway, you can find the divs with align="center" using:
var divs = document.getElementsByTagName('div');
var div;
var i = divs.length;
while (i--) {
div = divs[i];
if (div.getAttribute('align') == 'center') {
div.parentNode.removeChild(div);
}
}
Which will remove every div in the document that has align="center".
Note that the object returned by getElementsByTagName is a NodeList. If you iterate over it from 0 and remove nodes, they are removed from the live list so you will skip the node following the one you remove and you will attempt to access no existant nodes at the end. Going over the list backwards avoids these pitfalls. An alternative is to turn the NodeList into an array, but that's somewhat inefficient.
Edit
Since you edited the question, here's an update answer.
You can get a reference to the TR using getElementById:
var root = document.getElementById('-1');
Now you can go down the DOM:
var cell = root.cells[0]; // First cell in the row
var div = cell.getElementsByTagName('div')[0]; // first div
cell.removeChild(div);
Which is specific to the structure you've posted.
If you can just remove the content, you can use:
var all = document.getElementsByTagName("div");
for(i=0; i < all.length; i++) {
all[i].innerHTML = ""
}
See http://jsfiddle.net/7KVkC/
You need some way to make this div tag unique. There is another javascipt function called getElementsByTagName that you can use to get an array of all of the div tags. You can then use the DOM to check whether that div tag has the property of align="center".

Categories

Resources