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

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>

Related

How to dynamically remove elements in javascript?

Is there a way to dynamically remove elements with javascript or jquery. Suppose I have a function createElements() which creates new element and another function removeElement() which is suppose to remove the corresponding element. You will notice that when you run the snippet that when you click on the remove button all the element is gone! How could I implement this code? Isn't there a jquery selector where i could simply use removeElement(this) or somenething like that? Any suggestions are most welcome :) thank you.
function createElements() {
const boom = document.getElementById('boom');
boom.insertAdjacentHTML(
'beforeend', '<div class="newElem"><p >new element created dynamically yay!</p><button onclick="removeElement()">remove</button></div>'
);
}
function removeElement() {
alert('element removed dynamically boOoOoOoOooo!')
$('.newElem').remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boom">
</div>
<br>
<button onclick="createElements()">Create new element</button>
You can do it like this:
function createElements() {
const boom = document.getElementById('boom');
boom.insertAdjacentHTML(
'beforeend', '<div class="newElem"><p >new element created dynamically yay!</p><button onclick="removeElement(this)">remove</button></div>'
);
}
function removeElement(element) {
alert('element removed dynamically boOoOoOoOooo!')
$(element).parent(".newElem").remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boom">
</div>
<br>
<button onclick="createElements()">Create new element</button>
You just need to follow one single API. Use either pure JavaScript or jQuery. I would also suggest you to use unobstructive approach. Also, the way you remove the elements is wrong. You are removing everything.
See this way:
$(function() {
$("button#add").click(function() {
$("#boom").after('<div class="newElem"><p >new element created dynamically yay!</p><button class="remove">remove</button></div>');
});
$(document).on("click", ".remove", function() {
alert('element removed dynamically boOoOoOoOooo!')
$(this).closest(".newElem").remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boom">
</div>
<button id="add">Create new element</button>
To be able to always delete the div that encompasses the remove button, you have to traverse the DOM tree. There are lots of jQuery goodies for this: http://api.jquery.com/category/traversing/
In this particular case, I would do the following:
var elementCounter = 0;
function createElements() {
const boom = document.getElementById('boom');
boom.insertAdjacentHTML(
'beforeend', '<div class="newElem"><p >'+elementCounter+': new element created dynamically yay!</p><button onclick="removeElement(event)">remove</button></div>'
);
elementCounter++;
}
function removeElement(event) {
alert('element removed dynamically boOoOoOoOooo!')
$(event.target).closest('.newElem').remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boom">
</div>
<br>
<button onclick="createElements()">Create new element</button>
So you pass on the click event to the function as a parameter, and then with event.target you find out which button was clicked. $(event.target).closest(".newElem") will get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

How do I count the number of elements in a sortable div?

I have multiple divs in an HTML document with smaller divs within them that can be sorted among each other. When the document is loaded, a random amount of those smaller divs are appended to #boxtop.
Here's my HTML:
<html>
<body>
<head>
<title></title>
<script link src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="jquery-ui.min.css">
<link rel = "stylesheet" type" type="text/css" href = "style.css">
<script src="jquery-ui.min.js"></script>
<div id = "boxtop" class = "dragInto"></div>
<button type="button" id="button">My Children!!!</button>
<div id = "eqbox"></div>
<div id = "box1" class = "ansBox"></div>
<div id = "box2" class = "ansBox"></div>
<div id = "box3" class = "ansBox"></div>
</head>
</body>
</html>
Here's my relevent jQuery
$(document).ready(function()
{
$("#boxtop").sortable
({
connectWith: ".ansBox"
});
$(".ansBox").sortable
({
connectWith: ".ansBox"
});
});
$(document).ready(function()
{
$("dragInto").droppable
({
accept: ".box"
});
});
var numChild = $("#boxtop").length;
$(document).ready(function()
{
$("#button").click(function()
{
console.log(numChild);
});
});
My question is: How can I get the number of elements in a sorted div. I currently try and print that value to the console using numChild but that prints "1". And if I were to drag a bunch of elements from #boxtop to .box1, how could I get the number of elements inside .box1?
The .length property tells you how many elements belong to the jQuery object you call it on. So given that $("#boxtop") matches one element, $("#boxtop").length will be 1.
To find out how many elements are inside #boxtop you have to select all of its descendants and then check the .length:
// All descendants:
$("#boxtop").find("*").length // or:
$("#boxtop *").length
// Or count immediate children only:
$("#boxtop").children().length
In your case I think checking immediate children is probably what you want. But don't set a global variable like:
var numChild = $("#boxtop").children().length;
...because that will set numChild to the length when the page first opens, before the user has started interacting with it. You need to check $("#boxtop").children().length or $(".box1").children().length at the point where the value is needed.
As an aside, you don't need three separate $(document).ready(...) handlers: combine all of your code into a single ready handler, or if you put your <script> element at the end of the body you don't need a ready handler at all.
You need to catch update or stop event from sortable instance. Detailed document just right there
https://api.jqueryui.com/sortable/#event-stop
https://api.jqueryui.com/sortable/#event-update
Live Demo And Working Code

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');
});
});

getElementbyClassName not shown [duplicate]

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" />

Categories

Resources