I want to alert b if element is $("[id$=linkbuttonabsd]") and alert a otherwise.
JavaScript code:
$("body").find("a").click(function (e) {
var herf = $("body").find("a");
var link = $("[id$=linkbuttonabsd]");
var isb = false;
for (var i = 0; i < herf.length; i++) {
if (herf[i] == link) {
isb = true;
}
}
if (isb) {
alert("b");
} else {
alert("a");
}
});
But I can not achieve this by herf[i] == link. How should it be done?
$.fn.is() can be used.
Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
if(herf.eq(i).is(link)){
//Condition is ture
}
Also to get the element at specified index use .eq() rather than []
You don't need to loop through the objects. Code can be reduced to
$("body a").click(function(e) {
var herf = $("body a");
var link = $("[id$=linkbuttonabsd]");
var isb = herf.is(link);
if (isb) {
alert("b");
} else {
alert("a");
}
});
Try using $.is to match an element. Here is the example:
if ($(herf[i]).is("#linkbuttonabsd")) {
isb = true;
}
Related
I need to hide a <section> in my HTML with JavaScript while highlighting the text or to show it otherwise.
My selection works in this way:
document.addEventListener('click', function(){
var selected = window.getSelection();
var links = document.getElementsByClassName("linkAnnotation");
if (selected == '') {
links.setAttribute('style', 'display:block;');
} else {
links.setAttribute('style', 'display:none;');
}
})
but this setAttribute does not work as other hundreds of tries that I have done.
Can someone save my life??
Every setAttribute, style.innerHTML, etc.
when you are selecting links it retuns HTMLCollection forExample : [linkAnnotation1, linkAnnotation2] it not returns one element because your code doesnot works you must write for loop example:
document.addEventListener('click', function () {
var selected = window.getSelection();
var links = document.getElementsByClassName('linkAnnotation')
if (selected == '') {
for (let i = 0; i <= links.length - 1; i++) {
links[i].setAttribute('style', 'display:block')
}
}else {
for(let i = 0; i <= links.length - 1; i++) {
links[i].setAttribute('style', 'display:none')
}
}
})
getElementsByClassName returns a HTMLCollection (Which returns an array-like object of all child elements which have all of the given class name(s)). You have to iterate through all of those elements and change properties.
So, you have to use the following code:
document.addEventListener('click', function() {
var selected = window.getSelection();
var links = document.getElementsByClassName("linkAnnotation");
if (selected === '') {
links.forEach(val => { val.setAttribute('style', 'display:block;'); });
} else {
links.forEach(val => { val.setAttribute('style', 'display:none;'); });
}
})
I'd like to hide div content while checkbox is unchecked.
Here's my code
I've made almost the same function for the div with id "focus" (big grey frame):
document.getElementById("checkFocus").onchange = function() {
var one = document.getElementById("focus");
if (document.getElementById("checkFocus").checked === true) {
one.style.display = "block";
}
else one.style.display = "none";
}
And it works!
So, I don't understand why the next function doesn't works at all:
document.getElementById("checkMass").onchange = function() {
var elem = document.querySelector("PeriodicTable")
var mass = elem.querySelectorAll("div.element > div.mass");
if (document.getElementById("checkMass").checked === true) {
mass.style.display = "block";
}
else mass.style.display = "none";
}
What am I doing wrong?
elem.querySelectorAll("div.element > div.mass"); doesn't return a single element, it returns a collection of all matches.
That said you can't do mass.style.display on a array, only on a single element so you need to do
if (document.getElementById("checkMass").checked === true) {
for (var i = 0; i < mass.length; i++) {
mass[i].style.display = "block";
}
else {
for (var i = 0; i < mass.length; i++) {
mass[i].style.display = "none";
}
}
instead.
The querySelector("Any CSS rule") needs a rule, . signify class, # signify id, but you have querySelector("PeriodicTable"). Therefor you are looking for elements with tagname of PeriodicTable. Either use document.getElementById('PeriodicTable') or querySelector("#PeriodicTable")
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
Hi I am trying to compare two arrays to each other and then hide a list element if any of the values match.
One array is tags that are attached to a list item and the other is user input.
I am having trouble as I seem to be able to cross reference one user input work and can't get multiple words against multiple tags.
The amount of user input words might change and the amount of tags might change. I have tried inArray but have had no luck. Any help would be much appreciated. See code below:
function query_searchvar() {
var searchquery=document.navsform.query.value.toLowerCase();
if (searchquery == '') {
alert("No Text Entered");
}
var snospace = searchquery.replace(/\s+/g, ',');
event.preventDefault();
var snospacearray = snospace.split(',');
$('li').each(function() {
var searchtags = $(this).attr('data-searchtags');
//alert(searchtags);
var searcharray = searchtags.split(',');
//alert(searcharray);
var searchtrue=-1;
for(var i = 0, len = searcharray.length; i < len; i++){
if(searcharray[i] == searchquery){
searchtrue = 0;
break;
}
}
if (searchtrue == 0) {
$(this).show("normal");
}
else {
$(this).hide("normal");
}
});
}
Okay so I've tried to implement the code below but have had no luck. It doesn't seem to check through both arrays.
function query_searchvar()
{
var searchquery=document.navsform.query.value.toLowerCase();
if(searchquery == '')
{alert("No Text Entered");
}
var snospace = searchquery.replace(/\s+/g, ' ');
event.preventDefault();
var snospacearray = snospace.split(' ');
alert(snospacearray[1]);
$('li').each(function() {
var searchtags = $(this).attr('data-searchtags');
alert(searchtags);
var searcharray = searchtags.split(' ');
alert(searcharray[0]);
jQuery.each(snospacearray, function(key1,val1){
jQuery.each(searcharray,function(key2,val2){
if(val1 !== val2) {$(this).hide('slow');}
});
});
});
}
Working code:
function query_searchvar()
{
var searchquery=document.navsform.query.value.toLowerCase();
if(searchquery == '')
{alert("No Text Entered");
}
var queryarray = searchquery.split(/,|\s+/);
event.preventDefault();
$('li').each(function() {
var searchtags = $(this).attr('data-searchtags');
//alert(searchtags);
var searcharray = searchtags.split(',');
//alert(searcharray);
var found = false;
for (var i=0; i<searcharray.length; i++)
if ($.inArray(searcharray[i], queryarray)>-1) {
found = true;
break;
}
if (found == true )
{
$(this).show("normal");
}
else {
$(this).hide("normal");
}
});
}
var snospace = searchquery.replace(/\s+/g, ',');
var snospacearray = snospace.split(',');
Note that you can split on regular expressions, so to the above would equal:
var queryarray = searchquery.split(/,|\s+/);
To find whether there is an item contained in both arrays, use the following code:
var found = searcharray.some(function(tag) {
return queryarray.indexOf(tag) > -1;
});
Although this will only work for ES5-compliant browsers :-) To support the others, use
var found = false;
for (var i=0; i<searcharray.length; i++)
if ($.inArray(searcharray[i], queryarray)>-1) {
found = true;
break;
}
In plain js, without jQuery.inArray:
var found = false;
outerloop: for (var i=0; i<searcharray.length; i++)
for (var j=0; j<queryarray.length; j++)
if (searcharray[i] == queryarray[j]) {
found = true;
break outerloop;
}
A little faster algorithm (only needed for really large arrays) would be to sort both arrays before running through them linear.
Here's psuedo code that should solve your problem.
get both arrays
for each item in array 1
for each element in array 2
check if its equal to current element in array 1
if its equal to then hide what you want
An example of this coude wise would be
jQuery.each(array1, function(key1,val1){
jQuery.each(array2,function(key2,val2){
if(val1 == val2) {$(your element to hide).hide();}
});
});
If there's anything you don't understand please ask :)
I'm trying to hide elements with the same class name (float_form), but I'm also trying to use the script below to show them (all of the float_form class divs are initially hidden). I've looked at a lot of jquery solutions, but I can't seem to make any of them work for this.
function show(a) {
var e = document.getElementById(a);
if (!e)
return true;
if (e.style.display == "none") {
e.style.display = "block"
} else {
e.style.display = "none"
}
return true;
}
Edit: Sorry if it wasn't clear, I do not intend to use Jquery(and I know that this is not jquery). I am looking for a way to use javascript to recognize repeated classnames that are not in style= display:none; without compromising the show/hide ID element since there is a loop with the div id as the key. The html for the div looks like below, with {item.ID} being a while loop.
<div class="float_form" id="{item.ID}" style="display: none;">
vanilla javascript
function toggle(className, displayState){
var elements = document.getElementsByClassName(className)
for (var i = 0; i < elements.length; i++){
elements[i].style.display = displayState;
}
}
toggle('float_form', 'block'); // Shows
toggle('float_form', 'none'); // hides
jQuery:
$('.float_form').show(); // Shows
$('.float_form').hide(); // hides
If you're looking into jQuery, then it's good to know that you can use a class selector inside the parameters of $ and call the method .hide().
$('.myClass').hide(); // all elements with the class myClass will hide.
But if it's a toggle you're looking for, use .toggle();
But here's my take on a good toggle without using jQuery:
function toggle( selector ) {
var nodes = document.querySelectorAll( selector ),
node,
styleProperty = function(a, b) {
return window.getComputedStyle ? window.getComputedStyle(a).getPropertyValue(b) : a.currentStyle[b];
};
[].forEach.call(nodes, function( a, b ) {
node = a;
node.style.display = styleProperty(node, 'display') === 'block' ? 'none' : 'block';
});
}
toggle( '.myClass' );
Demo here (Click "Render" to run): http://jsbin.com/ofusad/2/edit#javascript,html
Using jquery
$(".float_form").each(function(){
if($(this).css("display") == "none"){
$(this).show();
}else{
$(this).hide();
}
});
No jQuery needed
const toggleNone = className => {
let elements = document.getElementsByClassName(className)
for (let i = 0; i < elements.length; i++){
if (elements[i].style.display === "none") {
elements[i].style.display = "";
} else {
elements[i].style.display = "none";
}
}
}
const toggleVisibility = className => {
let elements = document.getElementsByClassName(className)
for (let i = 0; i < elements.length; i++){
let elements = document.getElementsByClassName(className);
if (elements[i].style.visibility === "hidden") {
elements[i].style.visibility = "";
} else {
elements[i].style.visibility = "hidden";
}
}
}
// run
toggleNone('your-class-name-here'); // toggles remove
// or run
toggleVisibility('your-class-name-here'); // toggles hide
Answer provided in ES6 syntax but easily can be converted to ES5 if you wish
Try :
function showClass(a){
var e = [];
var e = getElementsByClassName(a);
for(i in e ){
if(!e[i])return true;
if(e[i].style.display=="none"){
e[i].style.display="block"
} else {
e[i].style.display="none"
}
}
return true;
}
demo : showClass("float_form");
How can I disable all hyperlinks in a div element? I don't want any active links in my div(editable).
jQuery:
$("#myEditableDiv a").click(function(e){ e.preventDefault(); });
Old and considered bad.
$("#myEditableDiv a").click(function(){ return false; });
using javascript you can write a simple method as given below -
function disableLinksByElement(el) {
if (document.getElementById && document.getElementsByTagName) {
if (typeof(el) == 'string') {
el = document.getElementById(el);
}
var anchors = el.getElementsByTagName('a');
for (var i=0, end=anchors.length; i<end; i++) {
anchors[i].onclick = function() {
return false;
};
}
}
}
//Call to function as
disableLinksByElement('mydiv');
First grab all the links.
var links = editable.getElementsByTagName('a'); // where "editable" is a var pointing to your div
Then set the onclick to false.
for (var i = 0; i < links.length; i++) {
var link = links[i];
link.onclick = function() { return false; };
}