javascript-getelement - javascript

what type of values given to getElementById() method

getElementById expects a string.
The following code:
var element = document.getElementById('myId');
finds the following element and assigns it to element
<div id="myId"></div>

just pass the id of any element
like <input type="text" id="text" />
just use getElementById("text")

a single DOM object, of a specialized class depending on the nature of the element identified by the given ID

Related

How to find and add the function to id?

I want to add a function to the attribute onChange of the element with id="custom-taxonomy". I don't want to edit the file.
I want to have a javascript solution.
My idea is to find the element by the id and then add the function.
How can i achiev this idea?
The code:
<div id ="custom-taxonomy">PRODUCT PRICES</div>
Expected result:
<div id ="custom-taxonomy" name="custom-product" onchange="return chothuephuongxa();>PRODUCT PRICES</div>
you can do that using setAttribute() and document.getElementById
let elm = document.getElementById('custom-taxonomy')
elm.setAttribute('name',"custom-product")
elm.setAttribute("onclick","return chothuephuongxa();")
console.log(elm.outerHTML)
<div id ="custom-taxonomy">PRODUCT PRICES</div>
Note:
You can't use name attribute of <div> but using elm.name = ... because name property in not available on <div> elements.
Similarly elm.onclick = "return chothuephuongxa();" is not correct because this will set event to string instead of function
You can use setAttribute to add attributes to elements:
document.getElementById('custom-taxonomy').setAttribute('name', 'custom-product');
the same can be done for your event.

Getting the value of an input element in jquery

I would like to get the value of a input using a the a chain class as the identifier in jquery. is this possible?
I have the following code
<input class="donate-block__value monthly" type="text" id="donation-amount" name="DonationAmount" value="200" />
and i have tried the following which has resulted in undefined
var monthlyDonation = $('.donate-block__value .monthly').val();
var monthlyDonation = $('donate-block__value monthly').val();
console.log(monthlyDonation);
I need to target the class Can this be done please?
Don't add space between your classes or jquery will start to search within the first class looking for a child element. use it like this:
var monthlyDonation = $('.donate-block__value.monthly').val();
You can also target just the input element in case you have multiple elements with that class defined:
$('input.donate-block__value.monthly').val();
Your selector .donate-block__value .monthly is referring to an element within an element. Try just .donate-block__value or .monthly

Get reference of object inside of div

I'm trying to reference an object inside of a div, using plain JavaScript:
<div id="main">
<div id="search">
<input type="text" id="query" />
<button onclick="test()">OK</button>
</div>
</div>
<script>
function test() {
try {
var main = document.getElementById("main");
var search = main.getElementById("search");
alert(search);
} catch (e) {
alert(e);
}
}
</script>
But I keep getting this error:
TypeError: main.getElementById is not a function(…)
Referencing main works, but not what's inside of main.
I also set up a Fiddle.
To find an element inside of other use querySelector
document.querySelector('#main #search')
As ID is unique, you can directly use
document.getElementById('search')
The reason for the error is there is no method called getElemetnById() attached to the Element object.
Since ID of an element must be unique there is need to do that, just use document.getElementById().
But if you want to make sure the said element is a descendant of anotehr element you can use document.querSelector('#main #search')
DOM Elements don't have getElementById method. Only document object have this method.
Id attribute specifies a unique id for the element.
It means only one element can have id="search". So you can use document.getElementById("search");

* selector works in getElementsByTagName(), but not for getElementsByClassName() in javascript?

I can use '*' selector in getElementsByTags(), but not in getElementsByClassName() or getElementByID().
Could someone explain why? And, is there anyway to use substring selector in javascript methods ie (getElementsByClassName("*profile") to select elements whose class name includes 'profile'?
The below is my code:
<body>
<div class="yahoo">
</div>
<p class="yahoo">
</p>
<ul class="yahoo">
</ul>
<div class="yahoo">
</div>
<input type='text'>
<script type="text/javascript">
function select(){
var elements = document.getElementsByTagName("*")
var elements2 = document.getElementsByClassName("*")
console.log(elements)
}
select()
</script>
This behavior conforms with DOM-Level-2-Core specification which states that:
getElementsByTagName
Returns a NodeList of all descendant Elements with a given tag name, in the order in which they are encountered in a preorder traversal of this Element tree.
Parameters
name of type DOMString
The name of the tag to match on. The special value "*" matches all tags.
There is no special notion for chracter * for getElementsByClassName method, which is treated literally as class name.
UPD. Addressing your second question:
is there anyway to use substring selector in javascript methods ie (getElementsByClassName("*profile") to select elements whose class name includes 'profile'?
You can't use getElementsByClassName however it's possible to use another very useful querySelectorAll method for this:
document.querySelectorAll('[class*="profile"]');

How to use document.getElementByName and getElementByTag?

document.getElementById('frmMain').elements
can i use like this
document.getElementByName('frmMain').elements
or
document.getElementBytag('table').elements`
document.getElementById('frmMain').elements
assumes the form has an ID and that the ID is unique as IDs should be. Although it also accesses a name attribute in IE, please add ID to the element if you want to use getElementById
document.getElementsByName('frmMain')[0].elements
will get the elements of the first object named frmMain on the page - notice the plural getElements - it will return a collection.
document.getElementsByTagName('form')[0].elements
will get the elements of the first form on the page based on the tag - again notice the plural getElements
A great alternative is
document.querySelector("form").elements
will get the elements of the first form on the page. The "form" is a valid CSS selector
document.querySelectorAll("form")[0].elements
notice the All - it is a collection. The [0] will get the elements of the first form on the page. The "form" is a valid CSS selector
In all of the above, the .elements can be replaced by for example .querySelectorAll("[type=text]") to get all text elements
getElementById returns either a reference to an element with an id matching the argument, or null if no such element exists in the document.
getElementsByName() (note the plural Elements) returns a (possibly empty) HTMLCollection of the elements with a name matching the argument. Note that IE treats the name and id attributes and properties as the same thing, so getElementsByName will return elements with matching id also.
getElementsByTagName is similar but returns a NodeList. It's all there in the relevant specifications.
I assume you are talking about getElementById() returning a reference to an element whilst the others return a node list. Just subscript the nodelist for the others, e.g. document.getElementBytag('table')[4].
Also, elements is only a property of a form (HTMLFormElement), not a table such as in your example.
It's getElementsByName() and getElementsByTagName() - note the "s" in "Elements", indicating that both functions return a list of elements, i.e., a NodeList, which you will access like an array. Note that the second function ends with "TagName" not "Tag".
Even if the function only returns one element it will still be in a NodeList of length one. So:
var els = document.getElementsByName('frmMain');
// els.length will be the number of elements returned
// els[0] will be the first element returned
// els[1] the second, etc.
Assuming your form is the first (or only) form on the page you can do this:
document.getElementsByName('frmMain')[0].elements
document.getElementsByTagName('table')[0].elements
If you have given same text name for both of your Id and Name properties you can give like document.getElementByName('frmMain')[index] other wise object required error will come.And if you have only one table in your page you can use document.getElementBytag('table')[index].
EDIT:
You can replace the index according to your form, if its first form place 0 for index.
The getElementsByName() method accesses all elements with the
specified name.
this method returns collection of elements that is an array.
The getElementsByTagName() method accesses all elements with the
specified tagname.
this method returns collection of elements that is an array.
Accesses the first element with the specified id.
this method returns only a single element.
eg:
<script type="text/javascript">
function getElements() {
var x=document.getElementById("y");
   alert(x.value);
}
</script>
</head>
<body>
<input name="x" id="y" type="text" size="20" /><br />
This will return a single HTML element and display the value attribute of it.
<script type="text/javascript">
function getElements() {
   var x=document.getElementsByName("x");
   alert(x.length);
   }
</script>
</head>
<body>
<input name="x" id="y" type="text" size="20" /><br />
<input name="x" id="y" type="text" size="20" /><br />
this will return an array of HTML elements and number of elements that match the name attribute.
Extracted from w3schools.

Categories

Resources