getElementbyClassName not shown [duplicate] - javascript

This question already has answers here:
getElementByClassName Not Returning Results
(2 answers)
Closed 8 years ago.
I´m using the following code
<script type="text/javascript">
function getInfo() {
var myElement = document.getElementbyClassName("contentMiddle");
alert(myElement.ClassName)
}
</script>
When i´m clicking on the button now:
<input onclick="getInfo" type="button" value="ClickMe" />
In the body is the div class="contentMiddle"> with a table inside. But nothing is shown when i´m clicking on the button.

It should be getElementsByClassName not getElementByClassName. i.e. Get Elements not Element. Unlike id of an element classname does not have to be unique for the document. There could be many elements with the same class name and function returns all of them.
It returns an array of all the elements with that class name. If you need to access a certain element you need to use the index.
<script type="text/javascript">
function getInfo() {
var myElements = document.getElementsByClassName("contentMiddle");
if(myElements != null)
{
alert(myElements[0].className);
}
else
{
alert("No elements found !");
}
}
</script>
HTML:
<input onclick="getInfo()" type="button" value="ClickMe" />

Related

How to select element by id which added using insertAfter? [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Attach event to dynamic elements in javascript
(15 answers)
Closed 6 months ago.
Using jquery I added an HTML button using insertAfter() now I would Like to select that button by id but didn't work.
$("button").click(function(){
$("<button id='new-button'>Added Button</button>").insertAfter("#this");
});
$("#new-button").click(function(){
$("<span> #new-button-work</span>").insertAfter("#this");
})
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<button id="this">Insert span element after this element</button>
</body>
</html>
Because of new-button is inserted after script run so you can try this
$("button").click(function(){
$("<button id='new-button'>Added Button</button>").insertAfter("#this");
});
$("body").on("click", "#new-button", function(){ <--
$("<span> #new-button-work</span>").insertAfter("#this");
})
Because you're dynamically adding new elements to the DOM you should use event delegation - attaching listeners to a parent element (like document), and then using the 2nd argument of the on method to identify the element you want to match.
$(document).on('click', '#this', function() {
const button = '<button id="new-button">Added Button</button>';
$(button).insertAfter('#this');
});
$(document).on('click', '#new-button', function() {
const span = '<span> #new-button-work</span>';
$(span).insertAfter('#this');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="this">Insert span element after this element</button>

jQuery Click event not firing on element click [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
Below is my html and javascript. The Js is located in a app.js file and the html is a yes or no question. At the bottom of the javascript I have code that should fire on click events. Right now it is just to see if it detects a click on the p elements in the html but hasn't worked so far.
Can anyone detect why this event isnt taking place?
The other jQuery int he code does work but this jQuery isnt invoked by a function and is invoked based of strictly using a selector which leads me to believe there is something wrong with how I used document.ready in my project.
Html:
<div class="question animated slideInUp">
<h3>Do you know your individual monthly rent cost?</h3>
<div class="rentanswer">
<p>Yes</p><p>No</p>
</div>
<!--
<p>If not, we'll get the average rent of a zip code for you from Zillow</p>
<form onsubmit="Obj(this.p.name,this.p.value)">
<input type="number" id="p" name="rent" placeholder="Leave blank if N/A" >
<input id="s" type="submit" value="Submit">
</form>
-->
</div>
Javascript:
var quest = ['../partials/income.hbs', '../partials/state.hbs', '../partials/rent.hbs', '../partials/zip.hbs', '../partials/roomate.hbs', "../partials/summary.hbs"];
var iterator = 0;
//creates object that gets sent to api
function Obj(name, vale){
event.preventDefault(); //prevents pg refresh
$('.form').load(quest[iterator], function () {
$('.bar p#' + name).css("border","2px solid black").addClass('enter').next().css({"border":"2px solid black","pointer-events":"auto","cursor":"pointer"});
});
//loads next html question to page
if(name){
data[name] = vale;
}
//move array accessor up to next question
iterator++;
console.log(data);
}
var data = {};
//user can click already submitted values to load that orignal question and change it/
function redo(q, id) {
q = Number(q);
//if the current queston on the page is not the one being clicked we then change it to the one being clicked
if (q + 1 != iterator) {
$('.form').load(quest[q], function () {
$('#p').val(data[id]);
});
iterator = q + 1;
};
};
$(document).ready(function(){
$('.rentanswer p').on('click',function(){
console.log('hey');
});
});
Here you go with a solution https://jsfiddle.net/g8xt5g4y/
$(document).ready(function(){
$(document).on('click','.rentanswer p',function(){
console.log($(this).text());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Do you know your individual monthly rent cost?</h3>
<div class="rentanswer">
<p>Yes</p>
<p>No</p>
</div>
I believe your HTML is getting rendered dynamically, that's why your click method isn't working.
Try event delegate (mentioned in th above code).
Hope this will help you.

Picking a random color from array [duplicate]

This question already has answers here:
How can I change an element's class with JavaScript?
(33 answers)
Closed 6 years ago.
I'm trying to program a button that randomly picks a color from the color array and chooses between these four values, and the color will be given to a new element.
They're classes that are defined in css. It's not working properly though as I don't see the issue with what I'm doing.
<script>
var colorArray = [ '.st1', '.st2', '.st3', '.st4'];
var randomColor = Math.floor(Math.random()*colorArray.length);
</script>
<label>
Class: <input type="text" id="new-class" value="randomColor">
</label>
<button type="button" onclick="addObject()">
Make Ball
</button>
Can anyone see to what I'm doing wrong?
To use a javascript variable as an HTML value, you have to set it in javascript. So to set your value attribute, do it like this:
And you need to wrap the code in the function that you set in the onClick
<script>
function addObject(){
var colorArray = ['.st1', '.st2', '.st3', '.st4'];
var randomColor = Math.floor(Math.random() * colorArray.length);
console.log(colorArray[randomColor]);
document.getElementById("new-class").className = colorArray[randomColor];
}
</script>

jQuery .click() not working in search suggestion [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
i want to create search suggestion. input type is created in this way:
<div class="signup_content_3">
<div class="signup_fieldName">
<p>
title
</p>
</div>
<div class="signup_text signup_input signup_search_parent" id="signup_flavorActor">
<input type="text" class="signup_searchType">
<div class="signup_suggestion">
</div>
</div>
my jQuery function to find key up is:
$('.signup_searchType').keyup(function(event){
$.ajax({url:"http://localhost:8000/auth/search/",success:function(result){
id=event.target.id;
var parent=event.target.parentElement.parentElement;
var add=parent.getElementsByClassName('signup_suggestion')[0];
add.style.display='block';
var child=add.firstChild;
while(add.firstChild){
add.removeChild(add.firstChild);
}
for(var i=0;i<Object.keys(result).length;i++){
var div=document.createElement('div');
div.innerHTML=result[i];
div.className='signup_oneSuggestion';
add.appendChild(div);
}
}})
});
and my jQuery click function is:
$('.signup_oneSuggestion').click(function(event){
console.log('click');
});
when i type in search type search suggestions appear but when i click on them does not print anything in console.
Use .on() (jQuery 1.7) with the element's ancestor, since it is created dynamically
$('.signup_suggestion').on('click', '.signup_oneSuggestion', function(event) {
console.log('click');
});
Dynamically created elements can be assigned an event in this way
$('body').on('click', '.signup_oneSuggestion', function(event) {
console.log('click');
});

Jquery: Toggle closest parent element using .on("click")? [duplicate]

This question already has answers here:
Why does click event handler fire immediately upon page load?
(4 answers)
Closed 9 years ago.
Given HTML such as
<div class="tpl grey">Hosts:
<p>Hi !</p>
<p>How are you ?</p>
<p>What ever.</p>
An other child & element type !
</div>
How to make that a click on a child element toggle the class="grey" of the closest parent .tpl element ?
The following code fails :
//Action to do on parent $(".tpl")
var switch1 = function () {
$(this).closest(".tpl").toggleClass("blue grey");
}
// On() click event
$(document).ready(function() {
$(".tpl").on("click", "p", switch1() );
});
Fiddle: http://jsfiddle.net/MRcCy/1
If you just want to toggle the closest .tpl (even though i only see one) try this
$(document).ready(function() {
$(".tpl p").click(function(){
$(this).closest('.tpl').toggleClass('grey');
});
});
Check this fiddle
$(document).ready(function() {
$(".tpl").click(function(){
$('.tpl').toggleClass('grey blue');
});
});

Categories

Resources