I want to query newly added div having memberCard class call but queryselectorall being static , i am not able to do so .How to resolve this problem?
var elementsToShow = document.querySelectorAll('.memberCard')
function list(){
$.ajax({
url:`http://localhost:8000/members`,
type:"GET",
success:function(members){
members.forEach(member => {
// Construct card content
content = `
<div class='memberCard'>
<div style='background-image:url("${member.image}")' class='memberImage'>
</div>
<div class='memberDetails josephine-sans'>
<h5>${member.name}</h5>
<h6>${member.batch}</h6>
</div>
</div>
`;
container.innerHTML += content;
});
}
You can use some hack i guess, update elementsToShow after success;
var elementsToShow = document.querySelectorAll('.memberCard')
function list(){
$.ajax({
url:`http://localhost:8000/members`,
type:"GET",
success:function(members){
members.forEach(member => {
// Construct card content
content = `
<div class='memberCard'>
<div style='background-image:url("${member.image}")' class='memberImage'>
</div>
<div class='memberDetails josephine-sans'>
<h5>${member.name}</h5>
<h6>${member.batch}</h6>
</div>
</div>
`;
container.innerHTML += content;
elementsToShow = document.querySelectorAll('.memberCard')
});
}
Use Event delegation and set the querySelector on the parent element.
This is an example :
<div id="button-container"></div>
// event is added for the parent of #submit-button
document.querySelector("#button-container").addEventListener('click',
function(e) {
if(e.target.id == 'submit-button') {
alert('CLICKED');
}
});
// #submit-button is dynamically created
document.querySelector("#button-container").innerHTML = '<button id="submit-
button">Submit</button>';
// click on #submit-button will now work
document.querySelector("#submit-button").click();
I suggesst you try to change your code , so you can use it this way.
Related
I want to read the html from a site and then split it into nodes. I tried this code:
function load() {
$(document).ready(function () {
$.get("https://example.com/index.html", function (data) {
const loadpage = async function() {
var nodes = [...data.childNodes].slice(-3);
var cont = document.getElementById("container");
var msg = nodes;
});
if(cont.innerHTML='') {
cont.insertAdjacentHTML('afterbegin', msg);
} else {
cont.innerHTML=msg;
}
};
loadpage();
});
});
}
load();
html looks like this:
<main>
<div class="msg">something</div>
<div class="msg">something</div>
<div class="msg">something</div>
<div class="msg">something</div>
<div class="msg">something</div>
<div class="msg">something</div>
</main>
the expected output should be:
<div class="msg">something</div>
<div class="msg">something</div>
<div class="msg">something</div>
since I want only the last 3 nodes.
Thank you.
It is not necessary to use async await here and you are doing it wrong
Please read How to return values from async functions using async-await from function?
Your load is also wrong and too complex. You should not add a window event handler in a function and the test to insert after if cont is empty is not useful. Your test is also not a comparison (== '' or === '') but an assignment (= '').
Add the data to a partial element and slice the result
$(document).ready(function() {
const cont = document.getElementById("container");
$.get("https://example.com/index.html", function(data) {
const div = document.createElement('div')
div.innerHTML = data; // assuming HTML string?
[...div.querySelectorAll('.msg')]
.slice(-3)
.forEach(div => cont.innerHTML += div.outerHTML);
});
});
EDIT: SOLVED. Thanks everyone!
I'm new to programming :D My code is below. Here is the deal: I have multiple buttons, but I want to make it so that the same thing would happen anytime any one of these buttons is clicked, but each button also has a specific value, and I also want that specific value to be printed out. My code goes through the document and looks at all the elements with "editButton" class, and correctly identifies all the buttons, but the problem is that no matter which button I press, I always get the value of the last button, because var id only gets assigned after the for loop finishes and is on the last element. I tried creating a global variable and assigning the value to it, but the result is the same. I tried ending the for loop before moving on to .done (function (data), but I got an error. Can someone help me out? Thanks!
$(document).ready(function() {
var anchors = document.getElementsByClassName('editButton');
for (var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
anchor.onclick = function() {
$.ajax({
method: "GET",
url: "/testedit.php",
}).done(function(data) {
var id = anchor.value;
/* from result create a string of data and append to the div */
var result = data;
var string = '<p>ID is ' + id + '</p><br>';
$("#records").html(string);
});
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="records"></div>
Actually, instead of doing a huge for loop to add onclick events to your buttons, one of the best ways to do this is to listen to each button with editButton class on click() event then use $(this) which refers to the exact clicked button. After that, you can use each individual button to do whatever you want.
So your final code should be something like this:
$(document).ready(function() {
$('.editButton').click(function() {
console.log('innerHTML is:', $(this).html())
console.log('id is:', $(this).attr('id'))
$.ajax({
method: "GET",
url: "/testedit.php",
}).done(function(data) {
var id = $(this).value;
/* from result create a string of data and append to the div */
var result = data;
var string = '<p>ID is ' + id + '</p><br>';
$("#records").html(string);
});
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="records">
<button class="editButton" id="firstButton">button 1</button>
<button class="editButton" id="secondButton">button 2</button>
<button class="editButton" id="thirdButton">button 3</button>
<button class="editButton" id="fourthButton">button 4</button>
</div>
save the button with button = this when run the onclick function and use it
$(document).ready(function(){
var anchors = document.getElementsByClassName('editButton');
for(var i = 0; i < anchors.length; i++) {
var button;
var anchor = anchors[i];
anchor.onclick = function() {
button = this;
$.ajax({
method: "GET",
url: "/testedit.php",
}).done(function( data ) {
/* from result create a string of data and append to the div */
var result= data;
var string='<p>ID is '+ button.value +'</p><br>';
$("#records").html(string);
});
}
}
});
https://jsfiddle.net/x02srmg6/
You need to look in to JavaScript closures and how they work to solve this.
When you add event listeners inside a for loop you need to be careful in JS. When you click the button, for loop is already executed and you will have only the last i value on every button press. You can use IIFE pattern, let keyword to solve this.
One simple way to resolve this issue is listed below.
<div id="records"></div>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var anchors = document.getElementsByClassName('editButton');
for(var i = 0; i < anchors.length; i++) {
//Wrap the function with an IIFE and send i value to the event listener
(function(anchor){
anchor.onclick = function() {
$.ajax({
method: "GET",
url: "/testedit.php",
}).done(function( data ) {
var id = anchor.value;
/* from result create a string of data and append to the div */
var result= data;
var string='<p>ID is '+id+'</p><br>';
$("#records").html(string);
});
}
})(anchors[i]);
}
}
});
You can read more about this in JavaScript closure inside loops – simple practical example
In your code..
var id = anchor.value;
could be
var id = anchor.id;
but I recommend you to use event delegation
If you have a html like this
<div id="buttonArea">
<a class="editButton" id="1"/>
<a class="editButton" id="2"/>
<a class="editButton" id="3"/>
.......(so many buttons)
</div>
you can code like below.
$(document).ready(function(){
$('#buttonArea').on('click', 'a.editButton', function (event) {
var anchor = event.currentTarget;
$.ajax({
method: "GET",
url: "/testedit.php",
})
.done(function(data) {
var id = anchor.id;
/* from result create a string of data and append to the div */
var result= data;
var string='<p>ID is '+id+'</p><br>';
$("#records").html(string);
});
}
You can use getAttribute. Like:
var anchors = document.getElementsByClassName('editButton');
// Id of anchors
id_of_anchor = anchors.getAttribute("id");
Refs
EDIT
anchor.onclick = function() {
id_of_anchor = $(this).attr("id");
});
You have jQuery in your application, there is easier and more readable way to do it with jQuery;
$(document).ready(function() {
$(".editButton").each(function(a, b) {
$('#' + $(b).attr('id')).on('click', function() {
$.ajax({
method: "GET",
url: "/testedit.php",
}).done(function(data) {
var id = $(b).attr('id');
/* from result create a string of data and append to the div */
var result = data;
var string = '<p>ID is ' + id + '</p><br>';
$("#records").html(string);
});
});
});
});
Example: https://jsfiddle.net/wao5kbLn/
Every time a selection is made from a dropdown menu, specific data is pulled from facebook and added to different divs. I am trying to update the contents of the div every time a different selection is made, however at the minute, the contents are just appended on after the initial contents.
This is the code that gets data based on a selection and creates the list from the returned data
<script>
city = document.getElementById("citySelection")
city.addEventListener("change", function() {
var selected = this.value;
var eventsList = document.getElementById("events");
if (selected == "None") {
eventsList.style.display = "none";
} else {
eventsList.style.display = "block";
};
if (selected == 'Bristol') {
getBristolEvents();
};
if (selected == 'Leeds') {
getLeedsEvents();
};
if (selected == 'Manchester') {
getManchesterEvents();
};
if (selected == 'Newcastle') {
getNewcastleEvents();
};
});
function createList(response, listId) {
var list = document.createElement('UL')
for (var i = 0; i < 10; i++) {
var events = response.data[i].name
var node = document.createElement('LI');
var textNode = document.createTextNode(events);
node.appendChild(textNode);
list.appendChild(node)
listId.appendChild(list);
}};
</script
This is the div being targeted:
<html>
<div id="events" style="display: none">
<div id="eventsDiv" style="display: block">
<div id="eventsListOne">
<h3 id='headerOne'></h3>
</div>
<div id="eventsListTwo">
<h3 id='headerTwo'></h3>
</div>
<div id="eventsListThree">
<h3 id='headerThree'></h3>
</div>
</div>
</div>
</div>
</html>
I have tried resetting the innerHtml of the div every time the function to get the data from facebook is called:
<script>
function getEventsThree(fbUrl, title) {
var listId = document.getElementById('eventsListThree');
var headerThree = document.getElementById('headerThree');
listId.innerHtml = "";
headerThree.append(title)
FB.api(
fbUrl,
'GET', {
access_token
},
function(response) {
listId.innerHtml = createList(response, listId)
}
)};
</script>
However, that still doesn't reset the contents of the div.
I've looked at other response but they all use jquery which I am not using.
Can anyone advise on the best way to fix this? Thanks.
I think your Hennessy approach is fine. Generate the inner content, then set .innerHTML.
At least one of your problems, maybe the only one, appears to be that you set .innerHTML to the return value of createList, but that function does not return anything.
<div id="history">
<div id="histheading" class="pull-left">History</div>
<div id='hist'><canvas id="test"></canvas></div>
</div>
var left=100;
var t=-150;
function doHistory_double()
{
var data = localStorage.getItem('HTML5TTT');
data = JSON.parse(data);
data.reverse();
var container = document.getElementById('hist');
// Clear the container
while (container.hasChildNodes())
{
container.removeChild(container.firstChild);
}
// Loop through the data
canvID = 0;
for(x in data)
{
var i=1;
var hist = data[x];
if(hist.datetime == undefined)
break;
var elem = document.createElement('div');
elem.style.marginLeft=lef + "px";
if(i==1){
elem.style.marginTop=t + "px";
}
else
elem.style.marginTop="0px";
i++;
elem.innerHTML = "<p><strong>"+hist.datetime+"</strong><br>Winner: "+hist.winner+"<br><canvas id='can"+canvID+"' width='100px' height='100px' ></canvas>";
container.appendChild(elem);
drawMiniBoard_double(document.getElementById("can"+canvID),hist.board);
canvID++;
lef+=310;
}
}
This is my javscript code. hist is a div showing history of the game.I am getting error as Cannot call method 'hasChildNodes' of null.I am getting this error after i did something using the variable left and t i.e margin-top and margin-left. Help me to solve this.
write it in a function and call it onload of document.
function deleteChildren() {
var container = document.getElementById('hist');
// Clear the container
while (container.hasChildNodes())
{
container.removeChild(container.firstChild);
}
}
<body onload="deleteChildren()">
<div id="history">
<div id="histheading" class="pull-left">History</div>
<div id='hist'><canvas id="test"></canvas></div>
</div>
</body>
its working perfectly.. check the fiddle
I have bind the click method then calling the code you provided and alert to show either we got a child inside the container or not..
--HTML--
<div id="history">
<div id="histheading" class="pull-left">History</div>
<div id='hist' onclick=f()><canvas id="test"></canvas></div>
</div>
-- JS --
function f()
{
var container = document.getElementById('hist');
// Clear the container
alert(container.hasChildNodes());
while (container.hasChildNodes())
{
container.removeChild(container.firstChild);
}
}
http://jsfiddle.net/FLC3R/
I'm trying to find the deepest element in the specified divwith jquery. But the code which used is producing the error TypeError: parent.children is not a function.
I found this code from this link
the code is :
function findDeepestChild(parent) {
var result = {depth: 0, element: parent};
parent.children().each( //Here I getting the error TypeError: parent.children is not a function
function(idx) {
var child = $(this);
var childResult = findDeepestChild(child);
if (childResult.depth + 1 > result.depth) {
result = {
depth: 1 + childResult.depth,
element: childResult.element};
}
}
);
return result;
}
---------------------------------------------------------------------------------------
$(document).on('keypress','#sendComment', function(e) {
if(e.keyCode==13){
var itemId=$('#findbefore').prev('.snew').attr('id');//
var item=findDeepestChild(itemId);
alert(item);
}
});
And my divs are :
<div id="S04" class="snew" style="display: block;">
<div class="author-image"></div>
<span>xyz shared the image xyz</span>
<div class="s-content">
<div class="s-message"></div>
<div class="shpicture">
<img class="SharedImage" width="100%" height="100%" data-shareid="1" data-alid="1" data-id="1" alt="xyz" src="data:image/jpeg;base64,">
</div>
</div>
</div>
<div class="SPcommentbox">
<div class="comment">
<div class="commenter-image"></div>
<div class="addcomment">
<input class="commentbox" type="text" placeholder="Write a comment...">
</div>
</div>
</div>
I need to find the img from these.
please anyone help me .... Thanks ...
To get the deepest nested elements, use
$("#" + parent).find("*").last().siblings().addBack()
http://jsfiddle.net/6ymUY/1/
you can then get the id data attribute with
item.data("id")
http://jsfiddle.net/6ymUY/2/
full code:
function findDeepestChild(parent) {
return $("#" + parent).find("*").last().siblings().addBack();
}
var item=findDeepestChild("S04");
console.log(item)
console.log(item.data("id"));
You're calling it with a string, but it's expecting a jQuery instance.
Instead of
var itemId=$('#findbefore').prev('.snew').attr('id');//
var item=findDeepestChild(itemId);
you probably want
var item=findDeepestChild($('#findbefore').prev('.snew'));
You are passing in itemId, which is the ID attribute of a given element. I think what you meant to pass was the element itself. Just remove the attr call, leaving this:
var item = findDeepestChild($("#findbefore").prev(".snew"));