How to find if parent Node has no Children - javascript

I'm not sure if I am using the correct syntax, as my ELSEIF doesn't appear to be firing. Is this the correct syntax, or what is the best way to test it?
<script>
function OnLoad() {
var links = document.getElementById("<%=TreeView1.ClientID %>").getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].setAttribute("href", "javascript:NodeClick(\"" + links[i].id + "\", \"" + links[i].getAttribute("href") + "\")");
}
}
window.onload = OnLoad;
function NodeClick(id, attribute) {
var nodeLink = document.getElementById(id);
if (nodeLink.hasChildNodes)
{
eval(attribute);
}
else if (nodeLink.hasChildNodes == false)
{
alert(nodeLink.innerHTML + " clicked");
window.open("../NewFolder/addNewProduct.aspx");
}
else
{
return;
}
}
</script>
If I move the alert/open window by itself it works, so I feel that the problem lies in this line:
else if (nodeLink.hasChildNodes == false)

The syntax for hasChildNodes says it is a method .i reckon changing it to a method should solve the problem
It should be noted, hasChiildNodes() considers whitespace and comments. From the MDN docs
childNodes also includes e.g. text nodes and comments. To skip them, use ParentNode.children instead.
i.e
if (nodeLink.hasChildNodes())
{
eval(attribute);
}
else if (!nodeLink.hasChildNodes())
{
alert(nodeLink.innerHTML + " clicked");
window.open("../NewFolder/addNewProduct.aspx");
}
else
{
return;
}
Check the two fiddles to get the difference
hasChildNodes fiddle .
ParentNode.Children fiddle

parentNode.children.length;
if it is 0, then no child node at all
For example
console.log(document.getElementById('d1').children.length); //->0
console.log(document.getElementById('d2').children.length); //->3
<div id="d1"></div>
<div id="d2">
<div></div>
<div></div>
<div></div>
</div>

Related

How to detect click outside an element with a class selector Using Pure Javascript (without using Jquery)

I want to detect clicking outside an element using class name as
selector
<div id="popOne" class="pop">...</div>
<div id="popTwo" class="pop">...</div>
...
<div id="popLast" class="pop">...</div>
<script>
var popElement = document.getElementById("pop");
document.addEventListener('click', function(event) {
var isClickInside = popElement.contains(event.target);
if (!isClickInside) {
alert("Outside");
//the click was outside the popElement, do something
}
});
</script>
As an alternative to iterating over all possible .pop elements for every click event, just traverse the DOM looking to see if the node or any ancestor thereof has the desired class:
document.addEventListener('click', function(e) {
var node = e.target;
var inside = false;
while (node) {
if (node.classList.contains('pop')) {
inside = true;
break;
}
node = node.parentElement;
}
if (!inside) {
alert('outside');
// click was outside
} else {
alert('inside');
}
});
This would make the performance scale relative to the depth of the DOM tree, rather than by the number of .pop elements.
Made the following changes to the script
var popElement = document.getElementsByClassName("pop");
document.addEventListener('click', function(event) {
for(i=0; i < popElement.length; i++){
popEl = popElement[i];
var isClickInside = popEl.contains(event.target);
if (!isClickInside) {
alert("Outside");
} else {
alert("Inside");
break;
}
}
});
First of all you are using the incorrect function to get Element. It should be getElementsByClassName("pop") and not getElementsById("pop") and also getElementsByClassName returns a HTMLCollection of elements having that class. So you need to loop over them and check whether clicked inside any of them or not. Here is the demo. Have added some style to divs so that it easy to differentiate between them. And also if need to check whether the click was on any of the divs then you need to check for that and as soon as you find that it was clicked inside a div having class pop. Break from the loop and continue with you conditions. But if for all the elements the IsClickedInside comes out to be false then you can handle it accordingly
document.addEventListener('click', function(event) {
var popElement = document.getElementsByClassName("pop");
var isClickInside;
for (var i = 0; i < popElement.length; i++) {
isClickInside = popElement[i].contains(event.target);
if (isClickInside) {
break;
//alert("Outside of" + popElement[i].id);
//the click was outside the popElement, do something
}
}
if(isClickInside){
alert("Clicked inside one of the divs.");
}else{
alert("Clicked outside of the divs.");
}
});
div {
height: 100px;
border:2px solid black;
}
<div id="popOne" class="pop">...</div>
<div id="popTwo" class="pop">...</div>
...
<div id="popLast" class="pop">...</div>
Hope it helps :)

Search for Text inside div

The problem is: I have one div that wraps all my users list. I want to make a search box, but i don't want to use Ajax, so i started trying JQuery, for search the text inside the div and hide the another results. I've tried but i'm stucked on this:
//Search Box
$(document).on('input', "#search-weeazer", function(e){
console.log('input ativado')
if($(this).val().length >= 4){
// if($('#colmeia-chat').html().indexOf($(this).val()) > -1){
// console.log('Found')
// } else {
// console.log('Not Found')
// }
$('div.chat-users>div').each(function(i,div){
if($(div).html().indexOf($(div).val()) > -1){
console.log($(div).html() + ' found: ' + i);
} else {
console.log("Not Found")
}
});
}
});
Someone know how i can do this?
Thanks!
In my HTML i have this:
<div class="chat-users" style="height: 400px;">
<?php include_once('user-chat-list.php'); ?>
</div>
Inside "chat-users" i have a list with all users, loaded with php
Here is more HTMl to show the structure:
https://jsfiddle.net/jdqbnz2w/
After Question Edit
Here is an updated JSFiddle based on the JSFiddle you included showing how to implement the search with your particular use-case:
JSFiddle
Original Answer:
You're missing some pertinent information in your question, such as "what does the HTML look like that comes from user-chat-list.php?" And because of that it makes it hard to understand exactly how your code applies.
Nevertheless, here is a simple example upon what you have provided that you can modify that does what you are looking for. You can run the following code snippet to see a working example:
var $searchBox = $('#search-weeazer');
var $userDivs = $('.chat-users div');
$searchBox.on('input', function() {
var scope = this;
if (!scope.value || scope.value == '') {
$userDivs.show();
return;
}
$userDivs.each(function(i, div) {
var $div = $(div);
$div.toggle($div.text().toLowerCase().indexOf(scope.value.toLowerCase()) > -1);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Search:
<input id="search-weeazer">
<p>Users:</p>
<div class="chat-users">
<div>Tony</div>
<div>Amber</div>
<div>Ronald</div>
</div>

How to change text in HTML by clicking

function diffSign(div) {
var sign = document.getElementById(div.id);
if (XXXXX) {
XXXXX
} else {
XXXX
}
}
<div data-toggle="collapse" data-target="#demo#(i.tostring)" id="Sign#(i.ToString)" onclick=diffSign(this)>+</div>
I want to change + sign to - and can change back!
THX
function diffSign(div) {
var sign = document.getElementById(div.id);
sign.innerText = (sign.innerText === "+") ? "-" : "+";
}
but if you pass in the div, why would you search it again?
function diffSign(div) {
div.innerText = (div.innerText === "+") ? "-" : "+";
}
would work too if the div parameter is the real div...
make sure this div has nothing other than the + or the - signs..
cheers.
The function's div Argument is already representing this by reference.
jsBin demo
function diffSign(div){
if (div.innerHTML === '+') { // If has "+"
div.innerHTML = '-'; // Set as "-"
} else { // else? well...
div.innerHTML = '+';
}
}
Or you can do it also like: jsBin demo using bitwise XOR (^=) and Ternary Operator(?:)
function diffSign(div) {
div.innerHTML = (div.io^=1) ? '-' : '+' ;
}
https://stackoverflow.com/a/22061240/383904
function diffSign(div) {
var sign = document.getElementById(div.id);
if (sign.innerHTML == '+') {
sign.innerHTML = '-';
} else {
sign.innerHTML = '+';
}
}
<div data-toggle="collapse" data-target="#demo#(i.tostring)" id="Sign#(i.ToString)" onclick=diffSign(this)>+</div>
Since div is the actual DOM element and a javascript object you can use it directly and add properties to it dynamically.
function diffSign(div) {
//Add a new property to maintain the element's state on the first call, toggle it on subsequent calls
div.useMinus = !div.useMinus;
//set the text based on the current state.
div.innerHTML = (div.useMinus ? '-' : '+');
}
you can use document.getElementById.innerHTML = "your new text"........ to change text.

Jquery Click Event on Form Input Not Running

I am creating a math problem website and in one page I have a part where the user clicks submit and it will check whether the answer is right or wrong.
Here is the main part of my code that I am having trouble with:
var newProblem = function(){
var textHide = true;
var submitTimes = 0
$("#content").append("<h2 class='middle_text'>Notice, this page is in BETA stage, improvement is still needed.</h2>")
$(".middle_text").fadeTo(1000,.8)
setTimeout(function(){$(".middle_text").fadeTo(500,0,function(){$(".middle_text").hide()})},4000);
setTimeout(function(){
var denominator = getNumbersEquivFrac.den()
var numerator = getNumbersEquivFrac.num(denominator);
var equivalent = getNumbersEquivFrac.equiv()
var problem = new equivalFrac(numerator,denominator,equivalent);
$("#content").append("<div class ='problem-choice' id='solve'>SOLVE THIS!</div>")
$("#content").append("<div class='problem-choice' id='answer'>SKIP AND GET ANSWER</div>")
$("#content").append("<div style='margin:auto; width:450px; text-align:center'><p id='question'>" + problem.printQuestion() + "</p>")
$("#content").append("<div id='instructions'></div>")
$("#question").fadeTo(750,1);
$(".problem-choice").fadeTo(750,1);
$("#solve").click(function(){
if(textHide === true){
$("#content").append("<form name='answer'><input class='problem-text' type='text' name='answer-input'><input type='button' class='problem-submit' value ='SUBMIT ANSWER'></form>");
$(".problem-text").fadeTo(300,.8)
$(".problem-submit").fadeTo(300,.8)
textHide = false
}
})
},4500)
}
newProblem();
$(".problem-submit").click(function(){
var checkAnswer = function(){
var answer = document.forms["answer"]["answer-input"].value;
if(answer === null || answer === ""){
alert("You must type in an answer.")
}
else{
submitTimes = submitTimes + 1;
if(answer !== problem.answer()){
if(submitTimes < 2){
$("#content").append("<div class='result' id='wrong'><div id='problem-des'><p>The correct answer was " + problem.answer() + "." + "</p></div><button id='next'>NEXT</button></div>");
$(".result").fadeTo(500,1)
}
}
else if(answer===problem.answer()){
if(submitTimes < 2){
alert("Correct!")
}
}
}
}
checkAnswer()
});
This is where the event is for the form submit button
$(".problem-submit").click(function(){
var checkAnswer = function(){
var answer = document.forms["answer"]["answer-input"].value;
if(answer === null || answer === ""){
alert("You must type in an answer.")
}
else{
submitTimes = submitTimes + 1;
if(answer !== problem.answer()){
if(submitTimes < 2){
$("#content").append("<div class='result' id='wrong'><div id='problem-des'><p>The correct answer was " + problem.answer() + "." + "</p></div><button id='next'>NEXT</button></div>");
$(".result").fadeTo(500,1)
}
}
else if(answer===problem.answer()){
if(submitTimes < 2){
alert("Correct!")
}
}
}
}
checkAnswer()
});
I don't know if it is the fact that the event is being called on a selector that was appended through the code and not originally in the html document.
I tried calling the event on parts of the page that were originally there, it worked.
But it isn't working for these, if you have any idea why, please say so.
You can asign an ID to your form, an use in the submit function:
$(document).on('submit','id_form',function(e) {
e.preventDefault();
}
Have you tried using using jquery's .on() function which essentially attaches the click event handler to any element that may have been created after the DOM was originally completed.
more info here: http://api.jquery.com/on/
$(".problem-submit").on('click',function(){
//function here
});

How to remove a div in a site using a Chrome extension?

There's this div in a site:
<div class="section1">
....
</div>
I want to remove it using a Chrome extension... Can someone give only the javascript code alone? Thanks.
function removeElementsByClassName(names) {
var els = document.getElementsByClassName(names),
i, element;
for (i = els.count - 1; i > 0; i -= 1) {
element = els[i];
element.parentElement.removeChild(element);
}
}
removeElementsByClassName('section1');
function removeElement(parentDiv, childDiv){
if (childDiv == parentDiv) {
alert("The parent div cannot be removed.");
}
else if (document.getElementById(childDiv)) {
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
}
else {
alert("Child div has already been removed or does not exist.");
return false;
}
}
removeElement('parent','child');
If by removing you simply mean hiding then you can run this from a content script:
document.querySelector('div.section1').style.display = 'none';
(this assumes there is only 1 section1 element on the page, otherwise you would need to use document.querySelectorAll and filter the results based on some criteria)

Categories

Resources