Why create loops to get elements for events? - javascript

The textbook I'm using to learn JavaScript uses the following code to display an alert dialogue whenever a user clicks on a paragraph:
var paras = document.getElementsByTagName("p");
for (var i=0; i<paras.length; i++) {
paras[i].onclick = function() {
alert("You clicked on a paragraph.");
}
}
I don't see the reason to loop through all the p elements, but instead identify them and simply attach the onclick event handler to it. Like this:
var paras = document.getElementByTagName('p');
paras.onclick = alert("You clicked on a paragraph.");
Doesn't that do the same thing? Why is it necessary to loop through the p elements?

No, that absolutely does not do the same thing:
You simply cannot attach event handlers to an HTML node list (well, you can, but nothing will happen);
You're trying to set the "onclick" to the result of the alert() statement, not a function as in your example. (Doesn't really matter because it won't work anyway.)
Now there is a way to handle the clicks with just one event handler, but I'll let you keep reading your book :-)
edit — To elaborate on point 2, this:
alert("hi");
is a function call. Its value will be whatever is returned from calling that function. Thus,
paras.onclick = alert("You clicked on a paragraph.");
sets the "onclick" property of the object that "paras" refers to, and it sets it to the value returned from alert() (which is probably always undefined).
As in the sample code from your book, things like "onclick" handlers need to be functions. That's what's going on in the middle of your sample code: the "onclick" property of each individual <p> DOM element is being set to a function. Inside that function is the call to alert().

Suppose you have
​<p>​First Paragraph</p>
<p>Second Paragraph</p>
<p>Third Paragraph</p>
So var paras = document.getElementsByTagName("p"); will return a collection of p like
[<p>​First Paragraph​</p>​, <p>​Second Paragraph​</p>​, <p>​Third Paragraph​</p>​]
If you write paras.onclick = alert("You clicked on a paragraph."); then it won't work because paras is an array of some p elements not the p element itself and only an html element has an event, so you have to loop through the collection and add event handler for each p element individually.
Even if you have only one p then it will return an array with one p element inside it, i.e.
​<p>​First Paragraph</p>
And var paras=document.getElementsByTagName("p"); will return[<p>​First Paragraph​</p>​]
So to add an event handler you can simply write
paras[0].onclick = function() { // 0 is the first element in the collection
alert(this.innerHTML);
}
Here is an example, I hope it'll help you to understand the process.

No, that will not work.
The function document.getElementsByTagName will return you an array of nodes because several nodes can have the same name (hence the plural for "Elements") : you can have several paragraph in you page, and this function will return them all. Even if you have only one paragraph, you will get an array containing one single element.
On the other hand, you could select the node with its ID by using the document.getElementById function. In this case, the result will be a single node, because IDs are supposed to be unique within a document.
var para = document.getElementByTagId('myParagraph');
paras.onclick = function(){ alert("You clicked on a paragraph.") };

Related

JavaScript focus a particular element with div class, not div id declaration

The following function can focus on an element with an id declaration:
function setFocus() {
document.getElementById("focus").focus();
}
But how can one focus on an element with a classname declaration. Use case would be previously in the code where the element we want to focus on is already stored from the dom (i.e., const element = document.querySelectorAll('.a-class-name')[0]) type of scenario?
Does the element have a tab index? You cannot focus a non input element unless it has a tab index. Use tabindex="-1" for elements like divs and spans. Then call the .focus() method on the element. -1 will allow you to focus with the focus method but wont get focus when move the focus around with the keyboard and pressing tab.
document.getElementById('btn').addEventListener('click', function() {
document.querySelectorAll('.focus_me')[0].focus();
});
<span class="focus_me" tabindex="-1">Focus me</span><br>
<button id="btn">Click to focus</button>
element.scrollIntoView(true) will do what you are needing.
document.getElementsByClassName('className') would always return multiple elements because conceptually Classes are meant to be applied to multiple elements. If you want only the first element in the DOM with that class, you can select the first element out of the array returned, as you did.
var elements = document.getElementsByClassName('className');
var requiredElement = elements[0];
OR
var requiredElement = document.querySelector('.className');
Then as #j08691 mentioned in the comments use
function setFocus() {
requiredElement.focus();
}
If the one with getElementById works, then there is no reason for this to not.
Happy coding. :)

Removing and creating HTML elements with same id using Javascript

I have a button that, when pressed, executes something like
function click(){
element = document.getElementById("element");
element.parentNode.removeChild(element);
var newelement = document.createElement("div");
body.appendChild(newelement);
newelement.id = "element";
}
I have also tried using element.outerHTML = "" instead of removeChild with no success. Before adding the bit about deleting the previous element with the id "element" things worked fine on the first click and an div named "element" was appended to the body. (Of course, on the second click, another element named "element" is appended, and I want to keep the id unique to one element.) Now, with the bit about removing previous elements, my button.onClick doesn't even do anything.
Another important piece of context: I'm trying to do this for elements that are generated using user input, so there's no guarantee on how many of these things are made--I just want them deleted when the user wants to generate more of them.
On the first click, I'm attempting to remove an empty element. Does that break something?
body does not exist in the scope you've provided and would throw an exception. I would try:
var body = document.querySelector("body");
See this for a example using your code:
https://jsfiddle.net/k0wL4y7p/2/
Also make sure you use var on all local variables so they are not declared globally. See below to learn about variable scope:
When to use var in Javascript
How about this... don't remove the Parent Element (Div1); instead to remove the children. Then, create the child and append it to the parent element.
Note: you must iterate over it to remove all child nodes & for p element id p1/p2 generate dynamic id or use class if you need it.
Your JS:
$(document).ready(function() {
$("#btn1").click(function() {
var element = document.getElementById("div1");
while (element.firstChild) {
element.removeChild(element.firstChild);
}
var para = document.createElement("p");
var node = document.createTextNode("New element after click.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
});
});
I prefer JQuery - no loop
$(document).ready(function(){
$("#btn1").click(function(){
$("#div1").empty();
$("#div1").append(" <p>Appended element after click</p>");
});
});
Your Html
<body>
<div id="div1">
<p id="p1">Paragraph element before click.</p>
<p id="p2">Another paragraph beofre click.</p>
</div>
<button id="btn1">Remove </button>
</body>
Hope it helps.

Getting String Value Of JavaScript Button

I have a list of buttons that is created by the DOM which references an array. When a button in the list is clicked, I want to retrieve the String that is displayed on the Button.
I have tried the following code to reference the string value, but get undefined:
this.String; inside the function when the button is clicked to retreive the string.
How can I properly retrieve the string.
The click handling function is:
$('.timeButtons').click(function() {
confirmation.push(this.textContent);
})
This is how the list of buttons is created:
var populateList=function(array){
var list = document.createElement('ul');
list.className="delete";
for(var i = 0; i < array.length;- i++) {
var item = document.createElement('li');
var itemButton=document.createElement('button');
itemButton.style.cssText='background:#f85a5a; border:none; width:200px; height:50px; margin-bottom:50px; align:center; border-radius:25px; color:#ffffff;'
itemButton.appendChild(document.createTextNode(array[i]));
item.appendChild(itemButton);
list.appendChild(item);
}
return list;
}
Assuming that this is a reference to the button element in question, you can use this.textContent to get the button's text. (Or .innerHTML.)
Demo: http://jsfiddle.net/w0ntsrLx/
Or since in your edited question you seem to be using jQuery, use the .text() method. In a comment you say that the containing div has the "timeButtons" class, so bind a delegated handler to that div as follows:
$(".timeButtons").on("click", "button", function(e) {
confirmation.push($(this).text());
});
Demo: http://jsfiddle.net/w0ntsrLx/1/
That way the function will only be called if the click is on a button element within the .timeButtons div, and this will be the clicked button. The click handler that you show in your question with $(".timeButtons").click(...) is bound to the div and doesn't in any way test for the buttons, so within the handler this will be the div, not the clicked button.
Check this out
Assuming you want pure javascript code,
Whenever an event is triggered, an object is passed back in callback (generally being named as 'event'). this object has many properties including source element, position of click and many more.
get the element using event.srcElement
You can use element.innerHTML or element.innerText to find out the content of the Button.
There is a difference between using innerText and innerHTML, but in your case, both can be used.
Also, you can use jquery too to easily append child, create elements and binding events.

Using remove as opposite of append not working

Here's how I append the value:
$('<div>someText</div>').appendTo(self);
And here's how I want to remove it:
$(self).remove('<div>someText</div>');
The appending works, the removing doesnt. What am I doing wrong?
The .remove() function takes a selector to filter the already matched elements, not to match elements inside of them. What you want is something like this:
$(self).find('div:contains(someText)').remove();
That will find a <div> element containing the text someText inside of whatever element self is, then removes it.
The API http://api.jquery.com/remove/ sais that a selector is required.
Try $(self).remove('> div');
This will remove the first childs of div.
You can use $(self).filter('div:contains("someText")').remove(); to remove a div with a specific content or $(self).find('> div').remove(); to remove the first childs of div.
EDIT: removed first version I posted without testing.
It most likely has to do with the scope of self. Since you've named it self I am assuming that you are getting this variable using $(this) on the click event. If that's the case, and you want to call the remove method, you can only do so from within the same function. Otherwise you need to either store the element in a variable or provide another selector to access it.
Example:
<div class="div1"></div>
this will be the div with the click event
$(document).ready(function(){
var self = null;
$('.div1').click(function(e){
self = $(this);
var itemToAdd = '<div>SomeText</div>';
$(itemToAdd).appendTo(self);
});
// to remove it
// this will remove the text immediately after it's placed
// this call needs to be wrapped in a function called on another event
$('.div1').find('div:contains(someText)').remove();
});

javascript get child by id

<div onclick="test(this)">
Test
<div id="child">child</div>
</div>
I want to change the style of the child div when the parent div is clicked. How do I reference it? I would like to be able to reference it by ID as the the html in the parent div could change and the child won't be the first child etc.
function test(el){
el.childNode["child"].style.display = "none";
}
Something like that, where I can reference the child node by id and set the style of it.
Thanks.
EDIT: Point taken with IDs needing to be unique. So let me revise my question a little. I would hate to have to create unique IDs for every element that gets added to the page. The parent div is added dynamically. (sort of like a page notes system). And then there is this child div. I would like to be able to do something like this: el.getElementsByName("options").item(0).style.display = "block";
If I replace el with document, it works fine, but it doesn't to every "options" child div on the page. Whereas, I want to be able to click the parent div, and have the child div do something (like go away for example).
If I have to dynamically create a million (exaggerated) div IDs, I will, but I would rather not. Any ideas?
In modern browsers (IE8, Firefox, Chrome, Opera, Safari) you can use querySelector():
function test(el){
el.querySelector("#child").style.display = "none";
}
For older browsers (<=IE7), you would have to use some sort of library, such as Sizzle or a framework, such as jQuery, to work with selectors.
As mentioned, IDs are supposed to be unique within a document, so it's easiest to just use document.getElementById("child").
This works well:
function test(el){
el.childNodes.item("child").style.display = "none";
}
If the argument of item() function is an integer, the function will treat it as an index. If the argument is a string, then the function searches for name or ID of element.
If the child is always going to be a specific tag then you could do it like this
function test(el)
{
var children = el.getElementsByTagName('div');// any tag could be used here..
for(var i = 0; i< children.length;i++)
{
if (children[i].getAttribute('id') == 'child') // any attribute could be used here
{
// do what ever you want with the element..
// children[i] holds the element at the moment..
}
}
}
document.getElementById('child') should return you the correct element - remember that id's need to be unique across a document to make it valid anyway.
edit : see this page - ids MUST be unique.
edit edit : alternate way to solve the problem :
<div onclick="test('child1')">
Test
<div id="child1">child</div>
</div>
then you just need the test() function to look up the element by id that you passed in.
If you want to find specific child DOM element use method querySelectorAll
var $form = document.getElementById("contactFrm");
in $form variable we can search which child element we want :)
For more details about how to use querySelectorAll check this page

Categories

Resources