How to return innertext of sibling element - javascript

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
}}

Related

How to select parent's sibling's children with javascript (without jquery)

I know that in jquery you can do this but how can it be done in pure javascript?
$(this).parent().siblings().find('.children').addClass("unselected");
Possible implementation of siblings():
const sib = (dir) => (node) => (
node[dir]
? [node[dir], ...sib(node[dir])]
: []
);
const prevSiblings = sib('prevSibling');
const nextSiblings = sib('nextSibling');
const siblings = (node) => [
...prevSiblings(node),
...nextSiblings(node),
];
Reference for getSiblings part.
document.onclick = e => {
var siblings = getSiblings(e.target.parentElement);
siblings.forEach(element => {
var children = element.querySelectorAll(".children");
children.forEach(el => {
el.classList.add("unselected");
})
})
}
var getSiblings = function(elem) {
// Setup siblings array and get the first sibling
var siblings = [];
var sibling = elem.parentNode.firstChild;
// Loop through each sibling and push to the array
while (sibling) {
if (sibling.nodeType === 1 && sibling !== elem) {
siblings.push(sibling);
}
sibling = sibling.nextSibling
}
return siblings;
};
.unselected {
color: red
}
<div>siblings div
<div>CLICK HERE</div>
</div>
<div>siblings div2
<div>OR CLICK HERE</div>
</div>
<div>siblings div3
<div class="children">div with class children</div>
</div>
<div>siblings div4
<div>OR CLICK HERE</div>
</div>
There is no direct analog for siblings() in DOM API.
this.parentNode.parentElement.querySelectorAll('.children')
.forEach(child => child.classList.add('unselected'));

How to move an HTML element's content from and to over and over?

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>

Why does my javascript code not not pass on the value from one div to another?

My goal is to take the value from one div and display it in another.
Here is the relevant html code:
<div id="main">
hello
</div>
The following is the function I have, which should take the number from the div I click on and display it in the div with the id 'main'.
function clr(e) {
var clickedElement = document.getElementById(e.currentTarget.id);
var currentXValue = clickedElement.innerHTML;
document.body.getElementById('main').innerHTML = currentXValue;
}
For some reason, the final line in the function does not do what I intend it to.
Here you go
function clr(e) {
var clickedElement = document.getElementById(e.id);
var currentXValue = clickedElement.innerHTML;
document.getElementById('main').innerHTML = currentXValue;// it should be document.getElementById not document.body
}
<div id="main">
Hello
</div>
<button onclick="clr(this)" id="Foo">Foo</button>
Please change document.body.getElementById('main').innerHTML to document.getElementById('main').innerHTML and it should work fine.
Hi please check this link http://jsfiddle.net/hidoos/Lpz917vo/
<div id="outer">
<div id="inner">heello</div>
</div>
<div id="result"></div>
and JS
var outer = document.getElementById('outer'),
result = document.getElementById('result');
outer.addEventListener('click', function (e) {
var html = '';
if (e.target === outer && e.currentTarget === outer) {
html += '<p>Outer element was clicked directly - it is <code>e.target</code> <em>and</em> <code>e.currentTarget</code>.</p>';
}
if (e.target !== outer && e.currentTarget === outer) {
html += '<p>Outer element is the current target, but it was not clicked directly - it is <code>e.currentTarget</code>.</p>';
}
html += [
'<ul>',
'<li><code>e.target === <div id="', e.target.id, '"></code></li>',
'<li><code>e.currentTarget === <div id="', e.currentTarget.id, '"></code></li>',
'<li><code>e.currentTarget === <div id="', e.currentTarget.innerHTML, '"></code></li>',
'</ul>'
].join('');
result.innerHTML = html;
});
u can add innerhtml
You can do something like this using Jquery.
$('div').click(function () {
$('#main').html($(this).html());
});
Here is a Jsfiddle:
https://jsfiddle.net/yuykhynm/1/

Trouble getting the index of a child when it is clicked

I'm trying to get the index of a child within a parent element. I followed the answer here, but ended up with an infinite loop.
My code so far:
var div = document.getElementById("spans");
var spans = div.getElementsByTagName("span");
div.addEventListener('click', function(e) {
var span = e.target;
var spanSiblings = 0;
while((span.previousElementSibling) != null ) {
spanSiblings++;
}
console.log(spanSiblings);
});
The aim is to output 0 when the user clicks on the first span because it's the first child in the "spans" id:
<div id="spans">
<span>This is span #1</span>
<span>This is span #2</span>
<span>This is span #3</span>
</div>
Any help would be appreciated.
As you are not changing the span variable in the loop, the condition will always be the same. If you assign the previous sibling to the variable, then it works:
var div = document.getElementById("spans");
var spans = div.getElementsByTagName("span");
div.addEventListener('click', function(e) {
var span = e.target;
var spanSiblings = 0;
while((span = span.previousElementSibling) != null ) {
spanSiblings++;
}
console.log(spanSiblings);
});
<div id="spans">
<span>This is span #1</span>
<span>This is span #2</span>
<span>This is span #3</span>
</div>
Borrowing a little from jQuery, which checks the elements position with $.inArray in it's index function, you can do
var div = document.getElementById("spans");
var spans = div.getElementsByTagName("span");
div.addEventListener('click', function(e) {
var span = e.target;
var arr = [].slice.call(spans);
var index = arr.indexOf( span );
console.log( index );
});
FIDDLE
You have to modify your while loop condition. You don't have any condition to terminate the while loop. Change your while loop code to
while((span = span.previousElementSibling) != null ) {
spanSiblings++;
}

how detect mouse click area in document - jquery - javascript

I have a page with a div element in it. i want when i clicked on outer area of that div element, then fade it out.
but i don't know how detect area of mouse click.
how detect that mouse click point is out of div area or not??
This is not very complicated - you have two options:
1. Asign onclick event to the outer area.
<div id="outer" onclick="$("#inner").fadeOut();">
<div id="inner" onclick="event.cancelBubble=true;/*disable bubling*/">Inner Div</div>
</div>
2. Traverse the dom and compare event.target (event.srcElement)
document.addEventListener("click", function(event) {
var body = document.body;
var target = event.target!=null?event.target:event.srcElement;
var inner = document.getElementById("inner");
while(target!=body) {
if(target==inner) //This means our inner element is clicked - or one of its children
return false;
target=target.parentNode; //Go UP in the document tree
}
$("#inner").fadeOut(); //If we got here, none of element matched our inner DIV, so fade it out
}
One possible jQuery solution:
$(document).on("click", function(e) {
var $div = $("#divId");
if (!$div.is(e.target) && !$div.has(e.target).length) {
$div.fadeOut();
}
});
DEMO: http://jsfiddle.net/5Jb5b/
function clickOn(e)
{
var target = e.target;
var optn = [];
optn.id = target.id;
optn.optnClass = target.className.split(' ');
optn.optnType = target.optnName.toLowerCase();
optn.parent = target.parentNode;
return optn;
}
document.body.onclick = function(e)
{
elem = clickOn(e);
var option_id = elem.id;
alert( 'option ID: '+option_id); // From id or other properties you can compare and find in which area mouse click occured
};

Categories