Update the id and not replace in javascript - javascript

The two functions in the javascript are both having a statement-
$('#'+key).html(data)
funtion data(data) {
$('#'+key).html(data)
}
funtion data2(data) {
$('#'+key).html(data)
}
which is essentially replacing the value of the key. I don't want the replacement but basically add to the same data and then render the new value.
I am very new to Javascript- will be glad if someone can point in the right direction.
Thanks in advance.

I don't want the replacement but basically add to the same data
Use append instead of html
$('#'+key).html(data)
funtion data(data) {
$('#'+key).append(data)
}
funtion data2(data) {
$('#'+key).append(data)
}

Without JQuery:
If you want to add just text, use appendChild:
function addText(divID, text) {
document.querySelector("#"+divID)
.appendChild(document.createTextNode(text));
}
/** TEST **/
var number = 1;
var intervalID = setInterval(addMore, 500);
function addMore() {
addText("appendHere", "Text #"+(++number)+" ")
// do not add infinitelly
if(intervalID>20)
clearInterval(intervalID);
}
<div id="appendHere"></div>
If you want to append HTML, just alter the code a bit:
function addHTML(divID, html) {
var fragment = document.createElement("span");
fragment.innerHTML = html;
document.querySelector("#"+divID)
.appendChild(fragment);
}

As per first comment of #gurvinder372
funtion data(data) {
$('#'+key).append(data)
}
funtion data2(data) {
$('#'+key).append(data)
}
This will help you to understand data handling on HTML elements using JQuery methods.

Related

Removing a created function in JavaScript

I have written this code by using some basics. I simply wanted to remove the image that I have created by using the function Generate() by a button. I have written the following code to remove the image generated. Please help me.
Please note that I have linked my button with the function Reset1(). Can someone give me the code to do the following please.
function Generate()
{
var image=document.createElement('img');
var div=document.getElementById('flex-box-gen');
image.src="https://thecatapi.com/api/images/get?format=src&type=gif&size=small"
div.appendChild(image);
}
function Reset1()
{
document.getElementById('Generate').remove();
}
You could either assign an id to your image element and use that to remove in your second function:
function generate() {
var image=document.createElement("img");
image.id = "image-01";
...
}
function reset() {
var image = document.getElementById("image-01");
var parent = image.parentNode;
parent.removeChild(image);
}
Or if there is nothing else in your containing div element you could just empty all elements from it:
function reset() {
document.getElementById("flex-box-gen").innerHTML = "";
}
getElementById will query a DOM element, not a javascript element.
What you can do, supposing you have only one img in your flex-box-gen is:
var imgs = document.querySelectorAll('#flex-box-gen img')
if(imgs.length > 0){
imgs[0].remove();
}
With a null-check in case the image was already removed
image.setAttribute('id',"Generate");
Add this line in generate function.

Remove innerHTML img completely by jQuery selection

I've dinamically created a div with the code below:
typebox.innerHTML += "<div id='idtypebox' class='typebox'><img id='typeImg' width='30px' height='30px' src="+d[o].src+"></div>";
My intention is to remove completely the innerHTML I created, by changing the innerHTML that had created the img and if change the form A to B, those images will be removed.
function SelectCheck() {
var select_val = $('#Check').val();
// using this to remove typeimg
var toRemove = document.getElementById('typeImg');
toRemove.parentNode.removeChild(toRemove);
if (select_val) {
ajax_json_gallery("Img/"+select_val);
}
return;
}
$(document).ready(function() {
$("#Check").change(SelectCheck).change();
});
I tried this code by on button and it works, but if I put in jQuery selection I get an error
var toRemove = document.getElementById('typeImg');
toRemove.parentNode.removeChild(toRemove);
Why not just :
$("#typeImg").remove();
And the complete code :
function SelectCheck(){
var select_val = $('#Check').val();
// using this to remove typeimg
$("#typeImg").remove();
if(select_val){
ajax_json_gallery("Img/"+select_val);
}
return;
}
jQuery(document).ready(function($) {
myVar=$("#d1 [href]").html();
var href = $(myVar).attr('src');
$("#d1").html('');
$("#d1").html('<img src="'+href+'" class="images_responsive_mode">').removeAttr("href");
});
</script>
this is one of the script which i created for remove the class assigned by wordpress and to assign new class for responsive image , if it useful for you do this !
you can use childNodes to remove the innerHtml
var toRemove = document.getElementById('typeImg');
toRemove.parentNode.removeChild(toRemove.childNodes[0])

Check if a specific hidden div exists and if not create one

I want to check if a specific hidden div exists and if not create one.
I do:
function myFunction(somestring) {
var myHiddenDiv = jQuery('<div id="js_method" style="display:none">');
...
myHiddenDiv.append(somestring);
}
The problem is this seems to create a new hidden div every time the function is called on the same page.
the hidden div just seems scoped to the function, whereas I want it scoped to the page.
Any tips.
tips please
Thanks.
Use length property:-
function myFunction(somestring) {
var myHiddenDiv;
if($("#js_method").length == 0){
myHiddenDiv = jQuery('<div id="js_method" style="display:none">');
$("body").append(myHiddenDiv);
}else{
myHiddenDiv = $("#js_method");
}
...
myHiddenDiv.append(somestring);
}
Why not just check by ID?
if (jQuery("#js_method").length == 0) {
var myHiddenDiv = jQuery('<div id="js_method" style="display:none">');
...
myHiddenDiv.append(somestring);
}

`.replaceChild()` on `this` Throwing NotFoundError: DOM Exception 8

I figured I would get fancy and use vanilla JavaScript during a jQuery event. The idea is that on click of a heading, I want to slide up a div (which works) and replace the tag clicked on to a larger heading.
From what I've read around, this can be caused by the parentNode referencing an element that's not the actual parent, but after checking it appears to be selecting the element that's directly above it.
So... here's the code!
HTML (in Jade)
.policy-container
h6.policy-heading Policies
.policy-list
.content-we-are-hiding
.not-actually-important
jQuery
$('.policy-heading').click(function() {
var self = this;
if (this.classList.contains('closed')) {
$(this).next().slideDown(300);
this.parentNode.replaceChild(self, '<h6 class="policy-heading">Policies</h6>');
} else {
$(this).next().slideUp(300);
this.parentNode.replaceChild(self, '<h2 class="policy-heading closed">Policies</h2>');
}
});
Everything seems pretty standard. Luckily I can just take care of this with jQuery, however I'd rather be using vanilla JS here. Any ideas why this isn't working?
As has been pointed out, replaceChild takes two nodes.
The following will work with native JS wrapped inside jQuery, as you've specified:
$('.policy-heading').click(function () {
var self = this,
h2 = document.createElement('h2'),
h6 = document.createElement('h6');
h2.class = "policy-heading closed";
h2.innerHTML = "Policies";
h6.class = "policy-heading";
h6.innerHTML = "Policies";
if (this.classList.contains('closed')) {
$(this).next().slideDown(300);
this.parentNode.replaceChild(h6, self);
} else {
$(this).next().slideUp(300);
this.parentNode.replaceChild(h2, self);
}
});
replaceChild takes two nodes, you are giving it a node and a string.
It looks like you'd be much better off just sticking with jQuery and using toggle functions for the sliding and class change.
try this :
.click(function(this)
you also need some debugging to understand what is going on I would advice you to use :
console.log(this)
use this :
el = document.createElement('h6');
el.class = "policy-heading";
el.innerHTML = "Policies";
this.parentNode.replaceChild(self, el);
As everyone pointed out, .replaceChild accepts two DOM elements, rather than the string like I was using. I also had its arguments backwards, the first is for the new element, the second is the replaced element.
Example code that works
$('.policy-container').on('click', '.policy-heading', function() {
var self = this,
newElement;
if (this.classList.contains('closed')) {
newElement = document.createElement( 'h6' );
newElement.classList.add('policy-heading');
newElement.innerHTML = 'Policies';
} else {
newElement = document.createElement( 'h2' );
newElement.classList.add('policy-heading');
newElement.classList.add('closed');
newElement.innerHTML = 'Policies';
}
$(this).next().slideDown(300, function() {
self.parentNode.replaceChild( newElement, self );
});
});

JavaScript Node assembling

I'm trying to create a function for rendering dom elements and I seem to be getting stuck with assembling more than one dom element before appending.
I've tried this: http://jsfiddle.net/RruyA/1/
And I can't seem to wrap my image with a link.
And using appendChild() where innerHTMl is now (marked with comment in the fiddle) produces an invalid pointer error.
I have a bunch of theories on what might be going wrong, but no solution yet. Help would rock!
Here's the full code:
(function () {
"use strict";
function tag (name, attributes, contents) {
var tag = {};
tag.name = name;
tag.attributes = attributes;
tag.contents = contents
tag.create = function () {
tag.element = document.createElement(tag.name);
for (var prop in tag.attributes) {
tag.element.setAttribute(prop, tag.attributes[prop]);
}
// This is the problem:
tag.element.innerHTML = contents;
}
tag.render = function () {
document.body.appendChild(tag.element);
}
return tag;
}
var p = tag('p', {'id':'details', 'class':'red nice lovely'}, 'Once upon a time in a golden castle on a silver cloud...');
var img = tag('img', {'src':'http://miyazakihayao.blog.com/files/2010/05/castle-in-the-sky-x1.jpg', 'width': '200px', 'alt':'Golden Castle'});
img.create();
img.render();
p.create();
p.render();
var a = tag('a', {'href':'http://google.com', 'target':'_blank'}, img.element);
a.create();
a.render();
}());
Your problem is that you are attempting to add text and HTML elements in the same way. Text will work fine with innerHTML although elements will be coerced to strings, and appendChild will add HTML elements, but you would need to wrap Strings in TextNodes.
So you can choose between those types and it works fine.
// This is a solution
if (contents) {
if (contents instanceof HTMLElement) {
tag.element.appendChild(contents);
}
else {
tag.element.innerHTML = contents;
}
}

Categories