I dont understand the why this UNDEFINED happen in JavaScript - javascript

Why this code return me undefined in the DOM when i don't put the [0]
var d = document.getElementsByName('msg')[0]
document.write(`<br> ${d.innerText}`)
<div id="msg" name="msg">click here</div>
just trying to understand JS in depth
var d = document.getElementsByName('msg')
document.write(`<br> ${d.innerText}`)
<div id="msg" name="msg">click here</div>

Because get elements will return a collection of elements not a single element
try get element by id

Related

Catch a html tag value with javascript

I have a div tag like
<div id="123" reference="r045">
Now I wanna save the value of the reference. I tried it with
var reference = document.getElementbyName("reference");
Didnt work. Any ideas?
Thanks :)
getElementbyName gets an element by its name.
The reference attribute:
Is not a name attribute
Is not valid HTML at all
So start by writing valid HTML:
<div id="123" data-reference="r045">
Then get a reference to that element:
const div = document.getElementById('123');
Then get the data from it using the dataset API:
console.log(div.dataset.reference);
Live demo
const div = document.getElementById('123');
console.log(div.dataset.reference);
<div id="123" data-reference="r045"></div>
You can use document.querySelectorAll('[reference]') if you have multiple div with same attribute.
var reference = document.querySelectorAll('[reference]');
console.log(reference);
<div id="123" reference="r045"></div>
But if you have only one div with reference attribute then use querySelector:
var reference = document.querySelector('[reference]');
console.log(reference);
<div id="123" reference="r045"></div>
var reference = document.getElementById("123").getAttribute("reference");
var x = document.getElementById("123").getAttribute("reference");
console.log(x);
<div id="123" reference="r045"></div>

How to handle spaces in div id in jquery

I am getting id of div from external source and in that spaces also coming in id , how to get the value of id. Here is my div example:
<div id="123456ABC" class="classname" onclick="javascript:AddValue(aa.value,'33',bb.value,'1000')"></div>
<div id="78904 bbc" class="classname1" onclick="javascript:AddValue(aa.value,'55',bb.value,'2000')"></div>
I need to get the class name from the id. Here is what I am doing:
function AddValue(aa, bb) {
var classOfDiv = $('#123456ABC').attr('class');
var classOfDivs = $('#8904 bbc').attr('class');
alert(classOfDiv);
alert(classOfDivs);
}
The first alert is working fine but second is not fetching a value. How can I handle this? All the values are dynamic.
Use $("div[id='78904 bbc']") to access element which has spaces in id, Try:
var classOfDiv = $("div[id='123456ABC']").attr('class');
var classOfDivs = $("div[id='78904 bbc']").attr('class');
alert(classOfDiv);
alert(classOfDivs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="123456ABC" class="classname" onclick="javascript:AddValue(aa.value,'33',bb.value,'1000')"></div>
<div id="78904 bbc" class="classname1" onclick="javascript:AddValue(aa.value,'55',bb.value,'2000')"></div>

Unable to Append Child in JavaScript using appendChild

I am trying to append some html which is coming as a string in a div but some how appendChild is not working as expected here is my JS code:
var doc = document.getElementById("products");
var notes = doc.getElementsByClassName("product_grid");
var str = '<div>New Node 3<div><div>New Node 4<div>';
var child = document.createElement('div');
child.innerHTML = str;
child = child.firstChild;
notes.appendChild(child);
Here is my HTML:
<div id="products" >
<div class="product_grid">
<div>
Existing node 1
<div>
<div>
Existing node 2
<div>
</div>
</div>
What is wrong with it its unable to Identify the appendChild as a function and keeps giving me error TypeError: notes.appendChild is not a function here is working fiddle
notes is a NodeList. So you'll have to use index to select the elements.
Try this:
notes[0].appendChild(child); // Appends to first product_grid

document.getElementById like function for a particular div

document.getElementById will search th whole document and return the result but here i want the same function for a particular div as i want to search the specific div for an id and based on that i want to execute
here is my code
if(document.getElementById('myId') ) // but it return the result from whole div
{
// Do something
}
else {
// do something else
}
i want something like
if(document.getElementById('myId') in specific div) \\ how to do this
Let say, you are looking for an element(div) with id "childId" within parent div with id "parentId". The Jquery code would be:
$("#parentId").find("#childId")
As a shortform, you can even do
$("#parentId #childId")
Since the above statement will find children in any depth, if you would want a direct child search, (first level child)
$("#parentId > #childId")
Generally ids are unique within the page (or atleast are recommended to be :) ). In such a case, you can directly do
$("#childId")
and still get the child element.
Whichever applies.
You want to search for a specific id for all div
I assume that you know the id you want to search
You can itenerate the document.getElementsByTagName('div') like this
var myID = 4;
for (var i = 0; i < document.getElementsByTagName('div').length; i++){
var res = document.getElementsByTagName('div')[i+1].id;
if(res == myID){
document.body.innerHTML = res;
break;
}
}
And this would be your HTML look like:
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>
<div id="6"></div>
See Demo here
Or I further assume that yor HTML code is look something like this:
<div id="myId">
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>
<div id="6"></div>
</div>
Then you can itenerate the document.getElementById('myId').getElementsByTagName('div') like this:
var myID = 3;
for (var i = 0; i < document.getElementById('myId').getElementsByTagName('div').length; i++){
var res = document.getElementsByTagName('div')[i+1].id;
if(res == myID){
document.body.innerHTML = res;
break;
}
}
And See Another Demo Here
id attributes should be unique, so searching an element with an id within another element it's the same as search for that id directly in the whole DOM.
You can return an element only if it is a child of a particular element by using a querySelector:
document.getElementById('evalBar').querySelector('#button_2');
/* returned value: (html BUTTON)
[object HTMLButtonElement]
*/
You could use the querySelector function. IMPORTANT: check browser compatibility!
https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector
Example:
<div id="foo">
<div id="bar">
this is foo-bar
</div>
</div>
<script>
var bar = document.querySelector("#foo #bar")
alert(bar.innerHTML); // result: alert message "this is foo-bar"
</script>

JQuery onclick attribute undefined in each() loop

Please forgive my awful coding style. I am learning to write a Chrome extension and can't figure out some JQuery stuff. I am trying to parse a document with some rows, each containing a (dynamically generated?) link, the HTML code looks like this:
<div class="row" id="rand">
<div class="display">
<div class="link">
<a name="actionLink" href="#" alt="action" onclick="listener.postAction('form', 'http://***/')" class="alink"><span>Confirm</span></a>
</div>
</div>
I am grabbing the info the following way:
$(".row").each(function(index)
{
var $itemArea = $(this).find(".display");
var id = $(this).attr("id");
var alink = $(this).find(".link").find("a");
var onclick = alink.attr("onclick");
console.log("id=" + id);
console.log("alink=" + alink);
console.log("onclick=" + onclick);
});
Here's the output from JSBin:
"id=rand"
"alink=[object Object]"
"onclick=listener.postAction('form', 'http://***/')"
However, when I debug this in Chrome, the value of "onclick" returned by my code is undefined. To make things more confusing, when I inspect the onclick attribute of alink, it shows the correct value? What am I doing wrong?
Try the following to get your var instead
var onclick = $('.link a:first',this).attr('onclick');

Categories

Resources