how to delete any content after jquery prepend() inside a loop - javascript

i am doing a search button and each time the user searches for a movie, i prepend the photos api in the html div. All i want to do is when a user searches again for another movie i want the previous content to be deleted, ( any content after the prepended one). Here is how my code looks like:
HTML:
<div id="Search-Results"></div>
jQUERY:
$.ajax(settings).done(function (response) {
for(var i=0; i < results.length; i++)
{
var s = '<span><img src="http://example.com/test.jpg"> </span>';
$("#Search-Results").prepend(s);
}
});
Example:
When the user searches for avatar movie and then for godfather, i want the avatar images to be deleted. The godfather will be pretended into the div and the avatar photos that are next to godfather will be removed.
Note that the code is inside a for loop and i get only 1 image with .html

Try this one
$("#Search-Results").html("");
for(var i=0; i < results.length; i++) {
var s = '<span><img src="http://example.com/test.jpg"> </span>';
if (i == 0){
$("#Search-Results").html(s);
}else {
$("#Search-Results").prepend(s);
}
}

For the very first photo in the loop use .html(), use .prepend() for the rest.
for(var i=0; i < results.length; i++) {
var s = '<span><img src="http://example.com/test.jpg"> </span>';
$("#Search-Results")[ i ? 'prepend' : 'html' ]( s );
}

This function will simply overwrite the innerHTML
$("#Search-Results").html(s);

Related

index number for the line time using JavaScript

I am using the below code in the google tag manager custom JavaScript variable, but it returns same index value for every line item, what can be the issue?
Web page link: https://www.amity.edu/programe-list.aspx?fd=all
function() {
var elements = document.querySelectorAll('.staff-container');
for (var i = 0; i < elements.length; i++){
(function(index){
elements[i].children[0].children[0].addEventListener("click", myScript);
function myScript(){
return("Clicked : ",index);
}
})(i);
}
}
There is an error in the 5th line.
It should be elements[index].children... in that case.
The updated code:
function() {
var elements = document.querySelectorAll('.staff-container');
for (var i = 0; i < elements.length; i++){
(function(index){
elements[index].children[0].children[0].addEventListener("click", myScript);
function myScript(){
return("Clicked : ",index);
}
})(i);
}
}
Here is an alternative way from Simo's blog
Blog link
Although the post is say about visibility element. I test it with click on my website.
This might work
function() {
var list = document.querySelectorAll('.staff-container a'),
el = {{Click Element}};
return [].indexOf.call(list, el) + 1;
}
If it is not working, you might need to provide the screenshot about the click element from your GTM preview.

How can I list the contents of all the <p> elements in the console using JavaScript?

I'm trying to log the content of all the <p> elements in the console by pressing on a button here is the code so far.
window.addEventListener("load",init);
function init(){
var b = document.getElementById("btn2")
b.addEventListener("click",action)
}
function action(){
var i, items = document.qetElementsByTagName("p");
for (i = 0; i < items.length; i++) {
console.log(items[i]);
}
}
Get content using innerHTML or textContent property
console.log(items[i].innerHTML);
//or
console.log(items[i].textContent);
(Plain JavaScript)
To list all "p" use
console.log(document.getElementsByTagName("p"))
Or use for first "p" only
//console.log(document.getElementsByTagName("p")[0])
To get content of first "p"
console.log(document.getElementsByTagName("p")[0].textContent)

For loop only running once in Jquery

Having an issue with a for loop in jQuery only running once. Users is a array containing 4 items, and for each, it should append that item as a list element to userList, which is a ul. It appends the first element in the array as expected, but only that one. Not sure why it isn't running through the entire array?
$(document).ready(function() {
var $currentUser = $('<li class="user"></li>');
for(var i = 0; i < users.length; i++) {
$currentUser.text(users[i]);
$currentUser.appendTo('.userList');
}
//alert(users.length) returns "4".
});
Try this
$(document).ready(function(){
for(var i = 0; i < users.length; i++) {
var $currentUser = $('<li class="user"></li>');
$currentUser.text(users[i]);
$currentUser.appendTo('.userList');
}
});
You're overwriting the element, instead of creating a new one for each user. Try the code above.
More jQuery'ish
$('.userList').append(function() {
return $.map(users, function(user) {
return $('<li />', {
'class' : 'user',
text : user
})
});
});
FIDDLE
You aren't adding a new <li> for each iteration:
Here's a working solution:
for (var i = 0; i < users.length; i++) {
$('<li class="user"></li>'
.text(users[i])
.appendTo('.userList');
}
https://jsfiddle.net/2abqa5us/1/
You create the li on the outside of the loop, then try to set the text of the same element to each user so you will overwrite it every iteration. Are you sure the last entry is not the one you see?
.text will overwrite previous text which looks like you got one users only
try this.
$(document).ready(function(){
for(var i = 0; i < users.length; i++) {
var $currentUser = $('<li class="user"></li>');
$currentUser.text(users[i]);
$currentUser.appendTo('.userList');
}
});

javascript removes only every second element

I've discovered a Problem ...
I'm writing a userscript for grease- and tampemonkey which should change a websites look.
One of my tasks is to remove every image with the title New Post
(<img src="..." title="New Post" alt="...">)
i have the following snipplet:
elements = document.getElementsByTagName('img');
alert(elements.length); // FIRST
for (i=0; i < elements.length; i++) {
image = elements[i];
if (image.title.search(/New\ Post/) > -1) {
image.remove();
}
}
alert(i); // SECOND
This snipplet removes images, but only every second.
The first alert gives me the number 19 but the second alert gives 10 ...
The script should delete every image tag with the given title.
What i'm doing wrong?
It looks like you're removing elements whilst looping through the list you're removing them from. At the point where you've removed more than are left, i is the same as elements.length so the loop exits before they're all removed.
Try removing them in reverse order:
for (i=elements.length - 1; i >= 0; i--) {
image = elements[i];
if (image.title.search(/New\ Post/) > -1) {
image.remove();
}
}
This way removing elements from the end of the list shouldn't affect your position in the list.
Because document.getElementsByTagName('img') returns a live list, that means when you call remove() on an element in the returned list the removed item will get removed from the array also.
document.getElementsByTagName
Returns an HTMLCollection of elements with the given tag name. The
complete document is searched, including the root node. The returned
HTMLCollection is live, meaning that it updates itself automatically
to stay in sync with the DOM tree without having to call
document.getElementsByTagName() again.
try
var log = (function() {
var $log = $('#log');
return function(msg) {
$('<p/>', {
text: msg
}).appendTo($log)
}
})();
var elements = document.getElementsByTagName('img');
log('initial: ' + elements.length);
for (i = 0; i < elements.length;) {
image = elements[i];
if (image.title.search(/New\ Post/) > -1) {
image.remove();
log('remove: ' + elements.length);
} else {
i++
log('not: ' + elements.length);
}
}
log('end: ' + elements.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img title="New Post" src="//placehold.it/64/fff000" />
<img title="New1 Post" src="//placehold.it/64/000fff" />
<img title="New Post" src="//placehold.it/64/fff000" />
<img title="New1 Post" src="//placehold.it/64/000fff" />
<img title="New Post" src="//placehold.it/64/fff000" />
<img title="New1 Post" src="//placehold.it/64/000fff" />
<div id="log"></div>
Only increment the loop counter if you're not removing an image:
for (i=0; i < elements.length; ) {
image = elements[i];
if (image.title.search(/New\ Post/) > -1) image.remove();
else i++;
}

How can I select all elements with the same class name?

I have a Boolean variable. It is stored in a hidden input field. Basically, if the user is signed in, it is false, if not, it is true.
There are download buttons which will link to a file download. My aim is to make it so that, if they aren't signed in, the button will not show, and the link will not work (it would be nice to have an alert saying they need to sign in or something, but that would probably be more effort than it's worth).
I have a function that performs onload of body:
function hide_download_btns(){
if (document.getElementById('download_btn_var_input').value == "true") {
document.getElementsByClassName('project_download_btn').item(0).hidden = true
}
}
My problem is where it asks for the nth term .item(0). This is where it selects the div on which to perform the function, however, I want the function to affect all divs with the class name 'project_download_btn'.
I'm not a fan of jQuery, so it would be great to avoid that if possible.
You can simply loop through the elements instead of just taking the 0th.
var buttons = document.getElementsByClassName('project_download_btn');
for(var i=0; i< buttons.length; i++){
buttons[i].hidden = true;
}
if (document.getElementById('download_btn_var_input').value == "true") {
var el = document.getElementsByClassName('project_download_btn');
for (var i = 0; i < el.length; i++) {
el[i].hidden = true;
}
}
document.getElementsByClassName returns array so what you are interested is :
document.getElementsByClassName('project_download_btn')[0]
Loop through each div that contains your download button and set hidden to true:
if (document.getElementById('download_btn_var_input').value == "true") {
var button_divs_array = document.getElementsByClassName('project_download_btn');
for (var i = 0; i < button_divs_array.length; i++) {
button_divs_array[i].hidden = true;
}
}

Categories