I get null when I try to do getelementbyid on dynamic loaded in div
I tried window.onload = function () { and $(window).load(function() {
index.html:
<main >
<div id="main-div">
</div>
</main>
homepage.html:
<!-- categories Slider -->
<div class="container-fluid">
<div class="site-slider-two px-md-4">
<div class="row slider-two text-center" id="homepageCategories">
javascript:
function loadHomePage() {
$("#main-div").load("homepage.html", function () {
}
}
function showCategoriesHomepage(categories) {
window.onload = function () {
homepageCategoriesId = document.getElementById(homepageCategories);
homepageCategoriesId.innerHTML = "";
//For loop that loops true all the categories
for (var i = 0; i < messages.length; i++) {
//Create dynamic li elements with child p elements
var mainDiv = document.createElement('div');
var span = document.createElement('span');
var img = document.createElement('img');
span.setAttribute("class", "border site-btn btn-span");
img.setAttribute("src", categories.image);
//Fills the p elements with user_id, description, created_at
span.appendChild(document.createTextNode(categories.name));
mainDiv.appendChild(img);
mainDiv.appendChild(span);
}
}
After the homepage is loaded I make a call to the api and after that is finished I try to getelementbyid on the div but it returns null
Change this line...
homepageCategoriesId = document.getElementById(homepageCategories);
...to this
homepageCategoriesId = document.getElementById('homepageCategories');
Related
In GTM i'm trying to return the inner text of a sibling element of the clicked element.
<div class="repair-item-n ">
<div class="repair-slide--54894d33-6c88-488f-95d7-3ec9b6a3ade4">
<div class="restoration_wrap text-center">
<img class="restoration-image">
</div>
<p class="title">Bags</p>
</div>
</div>
For example, on click of class "restoration-image" I want to return the value "Bags".
I have multiple occurrences of this HTML on the page with varinats such as "Shoes", "Hats" etc so I want to know on click of each, which would be the respective text of the "title" class
Try this:
var images = document.querySelectorAll('.restoration-image');
images.forEach(function (image) {
image.addEventListener('click', function (event) {
var parent = this.parentNode;
var nextSibling = parent.nextElementSibling;
alert(nextSibling.innerText)
})
});
This should work for GTM custom JavaScript variables.
function getImgTitle() {
if({{event}} === 'gtm.click') {
var image = {{Click Element}};
var parent = image.parentNode,
nextSibling = parent.nextElementSibling;
return nextSibling.innerText;
}
}
I would do this in a Custom Javascript Variable:
Click - Repair Item Title
function() {
var clickedEl = {{Click Element}};
if (!clickedEl) return;
// Find the mutual parent element
var repairItemEl = clickedEl.closest(".repair-item-n");
if (!repairItemEl) return;
var titleEl = repairItemEl.querySelector(".title");
if (!titleEl) return;
return titleEl.innerText
}}
How do I add the ability to drag certain content from one element over to another element, and back again, in pure Javascript?
I need this functionality to change the position of the content based on desktop and mobile sizes.
I have made my own function but the problem is that it's not possible to do the last action, to move the content to it's Original position again. It needs some bind functionality I think?
function moveContent(fromid, toid)
{
// Insert After This
var ref_el = document.getElementById(toid);
var parent = ref_el.parentNode;
// From Element
var from_el = document.getElementById(fromid);
if (from_el != null)
{
var from_el_parent = from_el.parentNode;
tparent = from_el.parentNode;
if (tparent === null || tparent.id !== toid)
{
var holder = from_el.outerHTML;
from_el.innerHTML = '';
// Insert inside
ref_el.innerHTML = holder;
}
}
}
Function example
function ChangeContent(aid,bid)
{
if((document.getElementById(aid)!=null)&&(document.getElementById(bid)!=null))
{
var atemp=document.getElementById(aid).innerHTML;
var btemp=document.getElementById(bid).innerHTML;
document.getElementById(aid).innerHTML=btemp;
document.getElementById(bid).innerHTML=atemp;
}
}
HTML example
<div id='A'><hr>
First div content<hr>
</div>
<div id='B'>
<strong>List</strong><br>
<ul>
<li>1</li>
<li>2</li>
<ul>
<li>3.1</li>
<li>3.2</li>
</ul>
</ul>
</div>
<input type='button' onclick='SwapContent(\"A\",\"B\");' value='Swap'></button>
Notes
You must place JavaScript after HTML, because otherwise JavaScript will not be able to find the elements to swap the content of.
Quotes in "onclick" function parameters are of this type because all code written for PHP+Html printing width ".
I'm not sure whether how practical your approach is but here is a JavaScript solution which will remove an element from the DOM and append it inside another element.
If the parent element doesn't have an id atribute, one is created using a Counter.
Restoring the element is simply a case of keeping track of the id of the parent element using a data-parent attribute.
(function() {
var Counter = function () {
if (Counter.prototype._singletonInstance) {
return Counter.prototype._singletonInstance;
}
Counter.prototype._singletonInstance = this;
this.getValue = function() {
if (this.value) {
this.value++;
} else {
this.value = 1;
}
return this.value;
};
};
function moveContent(fromId, toId) {
var from_el = document.getElementById(fromId);
var target_el = document.getElementById(toId);
if (from_el != null && from_el != target_el) {
var from_el_parent = from_el.parentNode;
var parent_id = from_el_parent.getAttribute("id");
if (!parent_id) {
// parent element doesn't have an id
// so generate a new parent id
var counter = new Counter();
parent_id = "gen_" + counter.getValue();
from_el_parent.setAttribute("id", parent_id);
}
if (!from_el.getAttribute("data-parent")) {
// the data-parent attribute is our route home
from_el.setAttribute("data-parent", parent_id);
}
// Insert After This
target_el.appendChild(from_el);
}
}
function restoreContent(id) {
var el = document.getElementById(id);
var parent = el.getAttribute("data-parent");
if (parent) {
// data-parent attribute exists
var target = document.getElementById(parent);
if (target) {
// target is valid
target.appendChild(el)
}
}
}
document.getElementById("switchAtoB").onclick = function switchAtoB() {
moveContent("contentA", "parentB");
}
document.getElementById("restore").onclick = function restoreA() {
restoreContent("contentA");
}
})();
#parentA {
background-color: #0aa;
min-height: 100px;
}
#parentB {
background-color: #aa0;
min-height: 100px;
}
<div>
<div id="parentA">
<div id="contentA">
<h1>Simple Title</h1>
<p>Lorem ipsum...</p>
</div>
</div>
<div id="parentB">
<div id="intro">
<p>Blah blah blah ...</p>
</div>
</div>
<div>
<button id="switchAtoB">A -> B</button>
<button id="restore">Switch Back</button>
</div>
</div>
I have a body element, and in this body element I have a child element with id fullpage. And this element contains child element with classname section. In function load_works() I add two more section elements
<body>
<div id="fullpage">
<div class="section">
<!-- Content -->
</div>
</div>
<script src="js/main.js" charset="utf-8"></script>
<script type="text/javascript">
load_works();
</script>
</body>
Contents of main.js:
function load_works() {
var container = document.getElementById('fullpage');
for (var i = 0; i < 2; i++) {
var new_section = document.createElement('div');
new_section.className = "section";
container.appendChild(new_section);
}
}
The problem is, that when I try to count section elements with getElementsByClassName() like this after load_works() is executed
function some_function() {
var sections = document.getElementsByClassName('section');
console.log(sections.length);
}
it always returns 1, and this, I think, is because I have only one static section element. querySelectorAll() of course and other get- fucntions also aren't working. So, how can I achieve the correct result with pure Javascript, not jQuery?
You better should place all javascript inside one file like main.js and then you only need to call some_function() after load_works().
function load_works() {
var container = document.getElementById('fullpage');
for (var i = 0; i < 2; i++) {
var new_section = document.createElement('div');
new_section.className = "section";
container.appendChild(new_section);
}
}
function some_function() {
var sections = document.getElementsByClassName('section');
alert(sections.length);
}
load_works();
some_function();
<div id="fullpage">
<div class="section">
<!-- Content -->
</div>
</div>
I need to create, decorate and append child 'divs' to existing. For example, after the appendChildren is executed, following divs
<div id="a">
<div id="b">
</div>
</div>
should take the following form (assuming decorateDiv adds text "This is new div" inside new div)
<div id="a">
<div id="b">
<div>"This is new div"</div>
</div>
<div>"This is new div"</div>
</div>
Here is my code
function appendChildren() {
var allDivs = document.getElementsByTagName("div");
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
decorateDiv(newDiv);
allDivs[i].appendChild(newDiv);
}
}
function decorateDiv(div) {
var x = document.getElementByTagName("div");
var t = document.createTextNode("This is new div");
x.appendChild(t);
}
I am completely new to JavaSpript. What am I doing wrong? Please help me to fix bugs
You're not using the parameter div and the decorateDiv should look like this:
function decorateDiv(div) {
//div is the object element
var t = document.createTextNode("This is new div");
div.appendChild(t);
}
The parameter 'div' that you are passing to function 'decorateDiv' has nowhere been used.
You can change your decorateDiv function like as below:
function decorateDiv(div) {
var t = document.createTextNode("This is new div");
div.appendChild(t);
}
Hope this helps!!
"allDivs" variable get update when to appendChild to any div because to stores array of elements of "div" TagName.
So, use class for fetching divs.
<div id="a" class="test">
A
<div id="b" class="test">
B
</div>
</div>
Here is user script:
function appendChildren() {
var allDivs = document.getElementsByClassName("test");
for (var i = 0 ; i < allDivs.length ; i++) {
var newDiv = document.createElement("div");
decorateDiv(newDiv);
allDivs[i].appendChild(newDiv);
}
}
function decorateDiv(div) {
var t = document.createTextNode("This is new div");
div.appendChild(t);
}
appendChildren();
And also you are not using parameter passed to decorative function.
This will work. Try this..
I have a div with HTML, that I am trying to push inside an empty div. The new div should acquire all the content and styling from the original.
Existing content:
<ul id="existing_id" class="my_class">
<strong>Does not show up in new div</strong>
<li class="style">
<p class="style">Shows up in new div</p>
</li>
</ul>
New, empty div - where I push everything from "existing_id" into:
<div id="empty_div"></div>
I am targeting the elements through JS:
var existing = document.getElementById("exisiting_id")
var existing_li = existing.getElementsByTagName("li")
var empty_div = document.getElementById("empty_div")
var myArray = []
empty_div.innerHTML = ""
// Pushing each existing li element inside myArray
for (var i=0; i < existing_li.length; i++) { myArray.push(existing_li[n]; }
function make_it_happen() {
empty_div.innerHTML += myArray.innerHTML
}
I am getting the content from #existing_id inside the new div - but not the styling associated with each element. Some elements are also ignored such as <strong>Does not show up in new div</div>
If you are wanting to collect all of the HTML from all of the LI elements into empty_div, you don't need myArray. The following should do:
var existing = document.getElementById("existing_id")
var existing_li = existing.getElementsByTagName("li")
var empty_div = document.getElementById("empty_div")
function make_it_happen() {
var html = '';
for (var i = 0; i < existing_li.length; i++) {
html += existing_li[i].innerHTML;
}
empty_div.innerHTML = html;
}