How do I check if a div contains another div? - javascript

I need to show alert if my parent div has a child div using JavaScript only No jQuery.
I have tried using the contains() function to check my div and send alert but it's not working.
<script type="text/javascript">
var parentDiv = document.getElementById("commentBox");
var childDiv = document.getElementById("comment1");
if (parentDiv.contains(childDiv)) {
alert("yes");
} else
{
alert("no");
}
</script>
<div class="row leftpad collapse" id="commentBox">
<div id="comment1">
<div class="col-md-3 dir-rat-left"> <i class="fa fa-user-circle" aria-hidden="true"></i>
<h6>James </h6>
</div>
<div class="col-md-9 dir-rat-right">
<p class="removemarg">always available, always helpfull that goes the same for his team that work with him - definatley our first phone call.</p>
</div>
</div>
</div>
There should be an alert box with message yes in it but it's not visible. I have also tried checking JavaScript using the alert() method only without any code.

Your code is running before the DOM is fully loaded. Move your script at the bottom of the page:
<div class="row leftpad collapse" id="commentBox" >
<div id="comment1">
<div class="col-md-3 dir-rat-left"> <i class="fa fa-user-circle" aria-hidden="true"></i>
<h6>James </h6>
</div>
<div class="col-md-9 dir-rat-right">
<p class="removemarg">always available, always helpfull that goes the same for his team that work with him - definatley our first phone call.</p>
</div>
</div>
</div>
<script type="text/javascript">
var parentDiv = document.getElementById("commentBox");
var childDiv = document.getElementById("comment1");
if (parentDiv.contains(childDiv)) {
alert("yes");
}
else{
alert("no");
}
</script>
OR: Wrap the code with DOMContentLoaded which will ensure that code placed inside will be executed only after the DOM is fully loaded:
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
var parentDiv = document.getElementById("commentBox");
var childDiv = document.getElementById("comment1");
if (parentDiv.contains(childDiv)) {
alert("yes");
}
else{
alert("no");
}
});
</script>
<div class="row leftpad collapse" id="commentBox" >
<div id="comment1">
<div class="col-md-3 dir-rat-left"> <i class="fa fa-user-circle" aria-hidden="true"></i>
<h6>James </h6>
</div>
<div class="col-md-9 dir-rat-right">
<p class="removemarg">always available, always helpfull that goes the same for his team that work with him - definatley our first phone call.</p>
</div>
</div>
</div>

You can use querySelector . If the child is not present it will give a null value
var hasChildDiv = document.getElementById("commentBox").querySelector("#comment1");
if (hasChildDiv !== null) {
alert('yes')
}
<script type="text/javascript">
</script>
<div class="row leftpad collapse" id="commentBox">
<div id="comment1">
<div class="col-md-3 dir-rat-left"> <i class="fa fa-user-circle" aria-hidden="true"></i>
<h6>James </h6>
</div>
<div class="col-md-9 dir-rat-right">
<p class="removemarg">always available, always helpfull that goes the same for his team that work with him - definatley our first phone call.</p>
</div>
</div>
</div>

let table = document.getElementById("niceTable");
let tds = table.getElementsByTagName("td");
for (let i = 0; i < tds.length; i++) {
tds[i].onclick = function () {
checkInputElement(tds[i]);
};
}
function checkInputElement(element) {
let input = element.querySelector("input");
console.log(element.contains(input));
}

Make sure that the whole DOM is loaded before you execute javascript code.
You can do this by adding the event listener DOMContentLoaded to your code or placing your scripts at the end of the file
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function(){
var parentDiv = document.getElementById("commentBox");
var childDiv = document.getElementById("comment1");
if (parentDiv && parentDiv.contains(childDiv)) {
alert("yes");
}
else {
alert("no");
}
}, false);
</script>
<div class="row leftpad collapse" id="commentBox" >
<div id="comment1">
<div class="col-md-3 dir-rat-left"> <i class="fa fa-user-circle" aria-hidden="true"></i>
<h6>James </h6>
</div>
<div class="col-md-9 dir-rat-right">
<p class="removemarg">always available, always helpfull that goes the same for his team that work with him - definatley our first phone call.</p>
</div>
</div>
</div>
You won't get an alert because parentDiv will not exist yet and the value will be null. This results that it does not contain the contains() function and it will throw an error. To be safe you can add a null check inside the if statement.

How about using window.onload function?
<script>
window.onload = function() {
var parentDiv = document.getElementById("commentBox");
var childDiv = document.getElementById("comment1");
if (parentDiv.contains(childDiv)) {
alert("yes");
} else {
alert("no");
}
}
</script>
This will execute the function until dom loads completely
<script>
window.onload = function() {
var parentDiv = document.getElementById("commentBox");
var childDiv = document.getElementById("comment1");
if (parentDiv.contains(childDiv)) {
alert("yes");
} else {
alert("no");
}
}
</script>
<div class="row leftpad collapse" id="commentBox">
<div id="comment1">
<div class="col-md-3 dir-rat-left"> <i class="fa fa-user-circle" aria-hidden="true"></i>
<h6>James </h6>
</div>
<div class="col-md-9 dir-rat-right">
<p class="removemarg">always available, always helpfull that goes the same for his team that work with him - definatley our first phone call.</p>
</div>
</div>
</div>

Related

How to select dynamic javascript dom element

I created a javascript script to create a couple of divs. Now i want to use javascript again but i can't get a way of doing it.
data.map((_r) => {
classesList.innerHTML += `
<div class="class" name=${_r.name} >
<div class="top">
<h1>${_r.name}</h1>
<i class="fas fa-arrow-down"></i>
</div>
<div class="bottom">
<p>${_r.count}</p>
</div>
</div>
`;
});
Using the document.querySelectorAll(".class") to get the inserted elements returns an empty NodeList
data = [{ name:'Steve',count:10 },{name:'Everst',count:1}];
let html='';
data.map((_r) => {
html += `
<div class="class" name=${_r.name} >
<div class="top">
<h1>${_r.name}</h1>
<i class="fas fa-arrow-down"></i>
</div>
<div class="bottom">
<p>${_r.count}</p>
</div>
</div>
`;
});
document.body.innerHTML=html;
let divs = document.querySelectorAll(".class");
console.log(divs)

how to make the button click executes code only one time

I want the button with the id #show-text-area execute the postButton(); function only once so it won't create a second elements whenever clicked (i want it to create it for only one time and won't work again until clicked another button).
Hope my question was clear enough.
HTML
<div id="post-creator" class="creator-container">
<div class="post-type">
<div class="text-post" id="post">
<button onclick="postButton();">Post</button>
</div>
<div class="media-post">Image & Video</div>
<div class="link-post">Link</div>
</div>
<div class="post-title">
<input type="text" class="title-text" name="post-title" placeholder="Title">
</div>
<div class="post-content">
</div>
<div class="post-footer">
<div class="spoiler">Spoiler</div>
<div class="nsfw">NSFW</div>
<button class="post">post</button>
</div>
</div>
Javascript
let postButton = function() {
let textarea = document.createElement('textarea');
textarea.setAttribute('class', 'post-data');
textarea.setAttribute('placeholder', 'Text (optional)');
document.querySelector('.post-content').appendChild(textarea);
}
You could disable the button after activation, this has the benefit of informing the user that further clicks won't do anything.
let postButton = function() {
let textarea = document.createElement('textarea');
textarea.setAttribute('class', 'post-data');
textarea.setAttribute('placeholder', 'Text (optional)');
document.querySelector('.post-content').appendChild(textarea);
document.getElementsByTagName("button")[0].disabled = true;
}
Otherwise you could simply have the function short-circuit if it has already been called.
// alreadyPosted is scoped outside of the function so it will retain its value
// across calls to postButton()
let alreadyPosted = false;
let postButton = function() {
// do nothing if this isn't the first call
if (alreadyPosted) { return; }
// mark the function as called
alreadyPosted = true;
let textarea = document.createElement('textarea');
textarea.setAttribute('class', 'post-data');
textarea.setAttribute('placeholder', 'Text (optional)');
document.querySelector('.post-content').appendChild(textarea);
document.getElementsByTagName("button")[0].disabled = true;
}
The following works.
let postButton = function(event) {
event.target.disabled = true;
let textarea = document.createElement('textarea');
textarea.setAttribute('class', 'post-data');
textarea.setAttribute('placeholder', 'Text (optional)');
document.querySelector('.post-content').appendChild(textarea);
};
document.getElementById('post').addEventListener('click', postButton);
<div id="post-creator" class="creator-container">
<div class="post-type">
<div class="text-post" id="post">
<button>Post</button>
</div>
<div class="media-post">Image & Video</div>
<div class="link-post">Link</div>
</div>
<div class="post-title">
<input type="text" class="title-text" name="post-title" placeholder="Title">
</div>
<div class="post-content">
</div>
<div class="post-footer">
<div class="spoiler">Spoiler</div>
<div class="nsfw">NSFW</div>
<button class="post">post</button>
</div>
</div>
You can also use hide show function on textarea if you do not want to create one.
let postButton = function() {
let d = document.getElementById('post_data').style.display;
if(d=='none'){
document.getElementById('post_data').style.display = 'block';
}
}
document.getElementById('post_data').style.display = 'none';
document.getElementById('post_btn').addEventListener('click', postButton);
<div id="post-creator" class="creator-container">
<div class="post-type">
<div class="text-post">
<button id="post_btn">Post</button>
</div>
<div class="media-post">Image & Video</div>
<div class="link-post">Link</div>
</div>
<div class="post-title">
<input type="text" class="title-text" name="post-title" placeholder="Title">
</div>
<div class="post-content">
<textarea class="post-data" id="post_data" placeholder="Text (optional)"></textarea>
</div>
<div class="post-footer">
<div class="spoiler">Spoiler</div>
<div class="nsfw">NSFW</div>
<button class="post">post</button>
</div>
</div>

Javascript Function back to it's original place

I'm not actually a programmer but I have to do this website work properly. And for that I'll need your help.
I'm messing with some javascript and I manage to maek this:
<script>
function funcaosabores1() {
document.getElementById("testeagora1").innerHTML = "";
document.getElementById('contento1').style.visibility="visible";
document.getElementById('contento2').style.visibility="hidden";
document.getElementById('contento3').style.visibility="hidden";
document.getElementById('contento4').style.visibility="hidden";
document.getElementById('contento5').style.visibility="hidden";
}
function funcaosabores2() {
document.getElementById("testeagora2").innerHTML = "";
document.getElementById('contento2').style.visibility="visible";
document.getElementById('contento1').style.visibility="hidden";
document.getElementById('contento3').style.visibility="hidden";
document.getElementById('contento4').style.visibility="hidden";
document.getElementById('contento5').style.visibility="hidden";
}
function funcaosabores3() {
document.getElementById("testeagora3").innerHTML = "";
document.getElementById('contento3').style.visibility="visible";
document.getElementById('contento1').style.visibility="hidden";
document.getElementById('contento2').style.visibility="hidden";
document.getElementById('contento4').style.visibility="hidden";
document.getElementById('contento5').style.visibility="hidden";
}
function funcaosabores4() {
document.getElementById("testeagora4").innerHTML = "";
document.getElementById('contento4').style.visibility="visible";
document.getElementById('contento1').style.visibility="hidden";
document.getElementById('contento2').style.visibility="hidden";
document.getElementById('contento3').style.visibility="hidden";
document.getElementById('contento5').style.visibility="hidden";
}
function funcaosabores5() {
document.getElementById("testeagora5").innerHTML = "";
document.getElementById('contento5').style.visibility="visible";
document.getElementById('contento1').style.visibility="hidden";
document.getElementById('contento2').style.visibility="hidden";
document.getElementById('contento3').style.visibility="hidden";
document.getElementById('contento4').style.visibility="hidden";
}
</script>
And I can't find on how to make for example: funcaosabores1 is clicked and is now visible, when I click funcaosabores2, the first one is hidden and the second is showing. But I can't click on the first one back because it was already clicked. (Idk if it's called return)
This is the div's called in the script:
<div class="animacao_saborgingerale" id="contento2" style="visibility:hidden;"></div>
<div class="animacao_saboruvasyrah" id="contento3" style="visibility:hidden;"></div>
<div class="animacao_sabortangerina" id="contento4" style="visibility:hidden;"></div>
<div class="animacao_saboruvabranca" id="contento5" style="visibility:hidden;"></div>
<div class="sabor-melancia"><p onclick="funcaosabores1()" id="testeagora1">MELANCIA</p> </div>
<div class="sabor-gingerale"><p onclick="funcaosabores2()" id="testeagora2">GINGER ALE</p></div>
<div class="sabor-uvasyrah"><p onclick="funcaosabores3()" id="testeagora3">UVA SYRAH</p></div>
<div class="sabor-tangerina"><p onclick="funcaosabores4()" id="testeagora4">TANGERINA</p></div>
<div class="sabor-uvabranca"><p onclick="funcaosabores5()" id="testeagora5">UVA BRANCA</p></div>
This seems quite messy but I'm here if you guys can help me! Thanks.
The CodePen of how it is right now. #nielsdebruin
I think you just want to do something like this:
let prevButton;
let prevContent;
function toggle(e) {
if (prevButton) prevButton.style.visibility = 'visible';
prevButton = e.target;
e.target.style.visibility = 'hidden';
let id = e.target.id;
let number = id.slice(-1);
if (prevContent) prevContent.style.visibility = 'hidden';
prevContent = document.getElementById('contento' + number);
prevContent.style.visibility = 'visible';
}
<div class="content animacao_saborgingerale" id="contento1" style="visibility:hidden;">1</div>
<div class="content animacao_saborgingerale" id="contento2" style="visibility:hidden;">2</div>
<div class="content animacao_saboruvasyrah" id="contento3" style="visibility:hidden;">3</div>
<div class="content animacao_sabortangerina" id="contento4" style="visibility:hidden;">4</div>
<div class="content animacao_saboruvabranca" id="contento5" style="visibility:hidden;">5</div>
<div class="button sabor-melancia"><p onclick="toggle(event)" id="testeagora1">MELANCIA</p> </div>
<div class="button sabor-gingerale"><p onclick="toggle(event)" id="testeagora2">GINGER ALE</p></div>
<div class="button sabor-uvasyrah"><p onclick="toggle(event)" id="testeagora3">UVA SYRAH</p></div>
<div class="button sabor-tangerina"><p onclick="toggle(event)" id="testeagora4">TANGERINA</p></div>
<div class="button sabor-uvabranca"><p onclick="toggle(event)" id="testeagora5">UVA BRANCA</p></div>

selecting elements javascript

I'm making a script that will notify you when someone is online on whatsapp web and i have this:
var onlineCheck = window.setInterval(function() {
var y = document.getElementsByClassName("emojitext ellipsify")[19];
if (y == null) {
console.log("online notification failed");
} else {
if (y.innerText === 'online') {
new Notification("contact is online");
window.clearInterval(onlineCheck);
}
}
},1000);
now the problem is that i'm selecting an element by the class "emojitext ellipsify" th 19th and if someone texts me another element with the class "emojitext ellipsify" will be made and the 19th won't be the status anymore, so i want to know if i can select an element with the same method from css which is : element>element
like this (div#main>header.pane-header pane-chat-header>div.chat-body>div.chat-status ellipsify>span.emojitext ellipsify)
or any other possible way.
var onlineCheck = window.setInterval(function() {
var y = document.getElementsByClassName("emojitext ellipsify")[19];
if (y == null) {
console.log("online notification failed");
} else {
if (y.innerText === 'online') {
new Notification("contact is online");
window.clearInterval(onlineCheck);
}
}
}, 1000);
<header class="pane-header pane-chat-header">
<div class="chat-avatar">
<div class="avatar icon-user-default" style="*somestyle*">
<div class="avatar-body">
<img src="*srcpath*" class="avatar-image is-loaded">
</div>
</div>
</div>
<div class="chat-body">
<div class="chat-main">
<h2 class="chat-title" dir="auto">
<span class="emojitext ellipsify" title="*person'sname*"><!-- react-text: 3216 -->*person'sname*<!-- /react-text --></span>
</h2>
</div>
<div class="chat-status ellipsify">
<span class="emojitext ellipsify" title="typing…"><!-- react-text: 3219 -->*the info that i need to get(typing…)*<!-- /react-text --></span>
</div>
</div>
<div class="pane-chat-controls">
<div class="menu menu-horizontal">
<div class="menu-item">
<button class="icon icon-search-alt" title="Search…"></button>
<span></span>
</div>
<div class="menu-item">
<button class="icon icon-clip" title="Attach"></button>
<span></span>
</div>
<div class="menu-item">
<button class="icon icon-menu" title="Menu"></button>
<span></span>
</div>
</div>
</div>
</header>
What you are looking for is document.querySelectorAll
With that function, you can select elements with a selector, the same used with css. So, you could do this:
document.querySelectorAll(".emojitext.ellipsify")
Or put a better selector, in order to get the desired elements, and not others.
Your example would be:
document.querySelectorAll("div#main>header.pane-header pane-chat-header>div.chat-body>div.chat-status ellipsify>span.emojitext.ellipsify")
You could use JQuery, much simpler
$('parent > child')
https://api.jquery.com/child-selector/

AngularJS - passing a value to a function for the second time returns undefined

I'm new to Angular and on my way to learn while bulding a website I've stopped with a really stupid moment.
I have a function inside a controller that is supposed to be called on ng-click event, I'm passing an 'id' value to it and using that 'id' it's supposed to search an array of presenters(objects) returning and assigning to $scope.presenter the one that I'm looking for. The thing is that the functions works ok for the the first time, but when I'm trying to call it again using a next/previous button the console log returns that the 'id' is undefined. Here is the controller code:
angular.module('fpl15App').controller('PresentersCtrl', function ($scope, $filter) {
$('body').css({'overflow':'hidden'});
$scope.showDetails = false;
$scope.currentPresenter = {};
$scope.getPresenterDetails = function( presenterId ) {
var id = presenterId - 1;
console.log(id);
$scope.showDetails = true;
var i=0, len=$scope.presenters.length;
for (; i<len; i++) {
if (+$scope.presenters[i].id === +id) {
return $scope.currentPresenter = $scope.presenters[i];
}
}
return null;
};
$scope.hideOverlay = function(){
$scope.showDetails = false;
};
$scope.presenters = [
{
id: 1,
name: 'adam_wolf',
thumb: 'images/presenters/adam_wolf.jpg',
bio: 'lorem ipsum'
}.
...
{
id: 15,
name: 'aimee_nicotera',
thumb: 'images/presenters/aimee_nicotera.jpg',
bio: 'lorem ipsum'
}
];
});
end here is the view code:
<div class="row" id="presenters">
<div class="col-md-12 above-element" id="presenter-overlay" ng-show="showDetails">
<div class="col-md-12 col-md-offset-6 motion-container animated" ng-class="{fadeInRight : showDetails}">
<div class="col-md-12 skew-container bg-yellow no-pad">
<div class="skew-content col-md-6 no-pad">
<div class="row presenter-image-container">
<div class="col-md-6 flex-container name-holder">
<h2>{{currentPresenter.name}}</h2>
</div>
<div class="col-md-6 no-pad image-holder">
<figure><img src="{{currentPresenter.image}}" alt=""></figure>
</div>
</div>
<div class="row bg-white presenter-bio-container">
<div class="col-md-6 col-md-offset-6">
<p>{{currentPresenter.bio}}</p>
</div>
</div>
<div class="row bg-white presenter-navigation">
<div class="col-md-10 col-md-offset-2">
<div class="row">
<div class="col-md-6 no-pad"> <span class="presenter-nav" ng-click="getPresenterDetails({{currentPresenter.id - 1}})"> <i class="glyphicon glyphicon-menu-left"></i> Prev </span> </div>
<div class="col-md-6 no-pad"> <span class="presenter-nav" ng-click="getPresenterDetails({{currentPresenter.id + 1}})"> Next <i class="glyphicon glyphicon-menu-right"></i> </span> </div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12 under-element">
<ul id="presenters-list">
<li class="presenter animation" ng-repeat="presenter in presenters"> <a ng-href="" ng-click="getPresenterDetails({{presenter.id}})"><img ng-src="{{presenter.thumb}}" alt="{{presenter.name}}"></a> </li>
</ul>
</div>
</div>

Categories