Getting a Javascript function to apply to all Elements by ID - javascript

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.

Related

How do I display a unique id value with GTM?

I have multiple elements on a page with the same class name, but each element has a unique id name.
Example:
<div class="video-image" id="get-googled">
<div class="video-image" id="email-marketing">
I want to display the id value, but right now I am only able to have GTM return and display the first element on the page. I read this post: "Getting value of ID from class" and it didn't help and even explains doing it the simple way will only display the first elements value.
Do I need custom Javascript to create this properly?
If you want to get a specific div and you know where it is on the page you might be able to use a DOM variable with an nth of type query selector. But this seems cumbersome, and since it seems you want a list in any case I think you are better of with a custom javascript variable:
function() {
return document.querySelectorAll(".video-image");
}
which return a collection of DOM elements (you might want to check if there are actually elements with that class first).
The initial answer is the right start - this completes the loop:
<script>
var inputs = document.querySelectorAll(".video-image");
for (var i = 0; i < inputs.length; i++) {
alert(inputs[i].id);
}
</script>
Here is a JSFiddle to try it out - [https://jsfiddle.net/JMurphy22/kduybmsp/2/][1]

Find all DOM elements of type HTMLButtonElement

I would like to scan a page for all DOM elements of type HTMLButtonElement so that I can get their exact position. I would then use this position to place another button on top.
I've been scanning through all DOM elements by the following code snippet:
var all = document.getElementsByTagName("*");
var temp = document.createElement('button');
for (var i = 0, max = all.length; i < max; i++) {
//Loop through all[i] to see if it is an object of type HTMLButtonElement
}
As already pointed out in comments, you can simply use:
document.getElementsByTagName("button");
The Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name. The subtree underneath the specified element is searched, excluding the element itself. The returned list is live, meaning that it updates itself with the DOM tree automatically. Consequently, there is no need to call several times Element.getElementsByTagName() with the same element and arguments.
– MDN's article on Element.getElementsByTagName()
Be aware though that HTML also has the <input type="button" /> element as well. If you want to pull these as well, you'd be better off using document.querySelectorAll() which allows us to specify multiple comma-delimited selectors:
document.querySelectorAll('button, input[type=button]');
Furthermore, you can also define button behaviour on elements by setting the ARIA attribute role to "button":
<div role="button">...</div>
If you also want to pull these, you can also include [role=button] in the above querySelectorAll call.

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!

How to get elements of similar name? jQuery

<input name="Indian_Karnataka_Bangalore" value="Bangalore" />
<input name="Indian_Andhra_Hyderabad" value="Hyderabad" />
<input name="Indian_Kerala_Trivandrum" value="Trivandrum" />
<input name="Indian_Maharashtra_Mumbai" value="Mumbai" />
At a given time, only one input element will be present in the DOM. How will I know the name of the specific input element name? I don't want to depend on values as it might change.
Using jQuery.
The INDIAN term will be static in every input element.
Actually i am trying to validate the input elements. DOM will have all the elements but at a given time only one element will be active and that element should have some value in it.
var $inputs = $('input[name*="Indian"]'),
inputsName = $inputs.attr('name');
You can use the same selectors as you would CSS.
Chris Coyier wrote a piece on attribute selectors here
var indianInputs = $("input[name^='Indian']");
//Matches all input elements whose name attrributes 'begin' with 'Indian'
This differs than the one posted by #ahren in that his selector will match all input elements whose name attribute contain the string 'Indian'.
indianInputs.attr("name");
Would return the first matched element's name attribute's value, which, for your markup will be Indian_Karnataka_Bangalore
To find the names of all indianInputs, you must iterate over all matched elements
var indianInputNames = [];
indianInputs.each(function() {
indianInputNames.push($(this).attr("name"));
});
$('input[name="element_name"]')
You have a lot of ways to select by the name of the attribute check http://api.jquery.com/category/selectors/attribute-selectors/
Try
var name = $('input[name^="Indian_"]').attr('name')
Have you tried the filter function? Something like this:
$('input:visible')
.filter(function() {
return $(this).attr("name").match(/^Indian/);
});
This will return an array of input elements whose name starts with "Indian".
There is a good example here: https://stackoverflow.com/a/193787/1237117.

Changing the ID of html elements

I have a form which allows user to add elements(which might be a field set or a text box) dynamically. I'm able to assign a new ID to the elements when added but I'm not able to make it in a sequence as the user can add elements in between as well.
So for example, there is an Id named XXX1 and the user adds a new element after it which is xxx2. Now if the user adds a new element again after XXX1, it comes up as XXX3. So the order of the elements is XXX1, XXX3, XXX2. I'm not able to control the names when it is being added. So I'm trying to re-assign the names after add.
I'm trying to get all elements in an array and change the ID as follows
document.getElementById('xxx3').setAttribute('id', 'xxx2');
But this doesn't work as ID XXX2 already exists for another element. Please help me with a solution for this.
So why not change the ID of xxx2 first, to move it out of the way, then putting it back in place later?
document.getElementById('xxx2').setAttribute('id', 'temporaryId');
document.getElementById('xxx3').setAttribute('id', 'xxx2');
document.getElementById('temporaryId').setAttribute('id', 'xxx3');
Why not go from the last element to the first(the one's after the position you are inserting to) and add one to the ID?
for example:
var insertAt = 2; // for an element to be called xxx2
var els = [...]; // an array with all of the elements
if(els.length >= insertAt){
for(var i = els.length-1; i >= insertAt-1; --i){
els[i].setAttribute('id', 'xxx'+(i+2));
}
}
// Add the new element here which will be called xxx2

Categories

Resources