How do access to element by name in javascript? - javascript

A page has elements without id - only with names. How to access them by javascript like this?
document.getElementById('id').value := "...";
UPDATED:
Thanks to all! Is it possible to access then to element with specified value (radiobutton)?
<nobr><label><input style="vertical-align:middle" type="radio" name="name" value="value1" checked="checked"/><span style="vertical-align:middle" class="label">value1</span></label></nobr><br/>
<nobr><label><input style="vertical-align:middle" type="radio" name="name" value="value2"/><span style="vertical-align:middle" class="label">value2</span></label></nobr><br/>

document.getElementsByName('name')
This returns a nodeList, which you can access like an array.

There is the DOM HTML getElementsByName method that returns a collection of nodes with that name. Note that the name property is not required to be unique, so you may get more than one and that the returned collection is live, so adding or removing elements with the subject name will modify the collection.

use document.getElementsByName('elementName'). this will give you an array-like collection, get the element by index

The other answers cover your original question. Regarding your update about accessing by value, there is no getElementsByValue() function, but if it is your intention to select the particular radio button that has both a specified name and value you can do something like this:
function getElementByNameAndValue(n, v) {
var els = document.getElementsByName(n),
i;
for (i=0; i < els.length; i++)
if (els[i].value == v)
return els[i];
return null;
}
var r = getElementByNameAndValue("name", "value1");
Above function will return a reference to the first matching element or null if nothing matched. If you want to allow for more than one element with the same name and value you could modify this to return an array (though I don't know why you'd have more than one element with the same name and value, at least not with radio buttons).
Note that also this can easily be modified to return a reference to the currently checked element, just change the if in the loop to be if (els[i].checked).
You may be able to do some or all of this using document.querySelector(), but I don't use it myself because I need to support older IE. You can definitely replace all of the above with one line of jQuery.

Related

After click show element in console

I need a help. I have a button in html with class "rekapitulace". And i want to do if a user click on that button, it will show a item in text input with class "jmeno". I wrote this but it isnt correct. Any solutions?
function rekapitulaceButton() {
var rekapitulaceButton = document.getElementsByClassName('rekapitulace')
rekapitulaceButton.addEventListener('click', precistUdaje)
}
function precistUdaje() {
var jmeno = document.getElementsByClassName('jmeno')
localStorage.setItem('local-jmeno', jmeno)
console.log(localStorage.getItem('local-jmeno'))
}
getElementsByClassName() returns all elements of provided class name, not just a single element. Notice how the name of that method contains plural elements word.
To get the first element, you can do:
const rekapitulaceButton = document.getElementsByClassName('rekapitulace')[0];
Another possibility is document.querySelector(), which always returns one element (first match) or null:
const rekapitulaceButton = document.querySelector('.rekapitulace');
document.getElementsByClassName('rekapitulace') return a nodelist array so if you need return an one node elment using id instead of class
document.getElementById('rekapitulace')
Note that you may be misusing localStorage for your debugging. The second argument of .set should be a string.
As mentioned already, you should really try to use IDs instead of classes for targeting the right input, and document.getElementsByClassName returns multiple elements and not just one element.

Set a check box with specific name as well as id as checked using javaScript

In my HTML file, I want to set a check box with specific name as well as id as= checked. How can I acheive this..?
eg:
<input type="checkbox" name="myName_1" id="1" value="my Value 1"> my Value 1
I know document.getElementById('id').checked = true;, but this only checks id. I need to check for id and name simultaneously using JavaScript. Pls help.
Edit:
More specific:
if(document.getElementById(1) && document.getElementById(1).type == "checkbox" ){
document.getElementById(1).checked = true;
}
Note: I have other elements that have same id, but different name, as well as same name, but different id. But no two have both in common.
Well, as i said IDs are always unique in the DOM. So having elements with the same ID is not valid.
You can however select by the name attribute with getElementsByName as this selection supports multiple element. It will just create a array that you can acces through the index value. So you can just loop through all the element and check them one by one:
var elem = document.getElementsByName('myName_1');
for(var i = 0; i < elem.length; i++)
{
elem[i].checked = true;
}
jsFiddle
Having id of HTML elements, starting with a number is incorrect. Rename your id and make it unique. Also value of id of 1 evaluates to true by javascript engine.
However if your HTML document is HTML5 compliant then id starting with a number is not problem.
You could do something like this, not ideal, but would solve the problem.
var names = document.getElementsByName(nameToFind);
names.forEach(funciton(item) {
if (item.id == idToFind)
item.checked = true;
});
As mentioned by several comments, it is not valid to have more than one element with the same id. If there are more than one of the same id, the behavior is unreliable.
If you have groupings of elements that are similar, a common convention with many developers is to give them a common class. This could/would replace your use of name. You can then search on elements within a certain class that have a specific id. (Which may be redundant, depending on your use.)
Searching by class is done with document.getElementsByClassName("myClass"), which returns an array of elements, similar to getElementsByName. Once you have this array, you can then loop through to determine if your id is within that class group[see note below] and apply effects as necessary. (e.g. elementArray[i].checked = true)
Note - It would be much more efficient to search for the id then determine the class, in my opinion.

Scan DOM and return or manipulate elements that have specific attributes prepended with specific string [duplicate]

This question already has answers here:
jQuery attribute name contains
(6 answers)
Closed 9 years ago.
I am trying to figure out how I can get a list of elements from the DOM (top to bottom) containing specific attributes that are prefixed with a given string lets say for the sake of example "monkey" is that string. If any exist.
I had this very loosely put together idea using $.each() and :contains but between the two I see no good coming from it. So I figured I'd come here to pick a few brains.
What I want to do is basically scan my dom when I call to a given function I will end up building up. That will seek elements with attributes that are prefixed with in this case "monkey" think of the data- attribute, and its use. Minus providing a specific selector, and not actually using the data- attribute.
Imagine this HTML
<div monkey-user="bar" monkey-permission="read">
<span monkey-user="bar" monkey-permission="read">some text</span>
</div>
<div>
<input type="text" monkey-user="bar" monkey-permission="none">
</div>
<input type="text">
<input type="text">
<input type="text">
<input type="text">
and then this javascript/jquery concept unless something cleaner can be used.
var arr = new Array();
$("*").each(function()
{
if($(this).children().length == 0)
{
if($(':contains("monkey-")',this))
{
arr.push($(this));
}
}
});
The result of arr in this case would be the 3 elements above with monkey- in them otherwise anything else is skipped. also worth noting is user/permission is for the sake of example, in the long run those can be other specific things that will be worked with on a per need basis (those in that case will be similar to working with the data attributes but Im thinking that will be another question for another time less someone wants to throw that in as a bonus.
You can try this way:
var arr = $("body").find('*').filter(function(){
var attrs = this.attributes; //get the attributes of the element
return ($.grep(attrs, function(o){
return /monkey/.test(o.name); //return the attributes that has name to be matched
}).length); //return the elements that has at least one of the matched attributes
}).get();
console.log(arr);
Fiddle
But note that these attribute names are not valid for an html element. Consider using data-* attributes instead
If you plan to use data-* then you can use data api(but this will select other data properties set as well which are not attributes of the element)
var arr = $("body").find('*').filter(function(){
var attrs = Object.keys($(this).data());
return ($.grep(attrs, function(o){
return /monkey/.test(o) === true;
}).length);
}).get();
Fiddle
But these methods can really slow down and are inefficient i would suggest you to add another attribute say data-hasmonkey to all the attributes that has your monkey- attributes. Then you can make an attribute selector more simpler and better: $("[data-hasmonkey]");

Mootools Selector issue

Right now I have a dynamic string that assigns it's values to a particular div class.
Output looks like this
<div class="12923"></div>
I want to find that 'randNumber' div, then check if it has another class 'x'
Currently what I have now doesn't work:
var randNumber = 12923
var lookingForYou = $$('.'+randNumber);
if (lookingForYou.hasClass('XCLASS')){alert('XCLASS FOUND!');}
$$ returns an Elements instance, Elements is an array-like Class
anyway since you are basically filtering, you can tell Slick that you need an element with both class:
var randNumber = 12923;
if($$('.' + randNumber +'.XCLASS').length>0){
alert('XCLASS FOUND');
}else{
//dostuff
}
or you could just use one of the Elements methods, I think .some will be your best choice here:
var randNumber = 12923
var lookingForYou = $$('.' + randNumber);
alert(lookingForYou.some(function(el){
return el.hasClass('XCLASS');
}))
EDIT:
adding some links:
A better way to use Elements on MooTools blog
in my second example I used the some method, which, by looking at the source is not overloaded, but is just the one in Array.prototype.some:
Element.js source reference
Array.some on MDN
$$ returns an array of all matching elems. Not sure if you can do a hasclass on an array. Might have to do a .each() then do it. Try $('body').getElement('.'+randNumber).hasClass('XCLASS') this way you grab 1 elem if you don't want to mess with the array.
Here:
if (lookingForYou.hasClass('XCLASS')){alert('XCLASS FOUND!');}
$$() returns an array, and hasClass() performs the check on each element of the array, returning an array of booleans. Unfortunately, when you check if (...), then the return array, even if all of the values are false, is evaluated as true because it's non-empty.

How to get all elements with a given property?

I'd like to get all <input /> elements with the placeholder property set, how could I do this without jquery? it should support IE6+, and other popular browsers.
Assuming all the fields have an ID
DEMO
var fieldsWithPlaceholder = [];
var inputs = document.getElementsByTagName("input");
for (var i=0, n=inputs.length;i<n;i++) {
if (inputs[i].getAttribute("placeholder") !=null) {
fieldsWithPlaceholder.push(inputs[i].id);
}
}
alert(fieldsWithPlaceholder);
Update: you can as posted elsewhere test for null, undefined or blank in one go:
if (inputs[i].getAttribute("placeholder")) { // there is something there
Use getElementsByTagName, filter for those with a placeholder property value that isn't undefined.
Incidentally, there is a big difference between attributes and properties, which are you really after? If you are setting an attribute called placeholder in the HTML, then you should use getAttribute. However, if you are setting the property of a DOM element (which is what I presumed from your post) then you should use the property directly. Hopefully you aren't mixing the two.
In some browsers, attributes and properties are kept synchronised but in others they aren't. For example, Firefox will not create element properties for non–standard attributes (i.e. those that aren't specified in the related markup standard), nor will it create or modify standard attributes based on property changes in versions that aren't consistent with HTML5.
get all the elements of type input first
document.getElementsByTagName("input")
loop over the above list and then use the
getAttribute on each of the element as follows getAttribute("placeholder") if it is not null or undefined then the input has it set.
Try something like this:
var myEls = [],
allEls = document.getElementsByTagName('input');
for (var i=0; i < allEls.length; i++) {
if (allEls[i].placeholder)
myEls.push(allEls[i]);
}

Categories

Resources