Simple JavaScript Selector - javascript

Using pure JavaScript without any library like jQuery, how could I detect if a variable holds a DOM Class or ID?
For example if I pass into a function a value that could be...
var mySelector = ".class-name";
or
var mySelector = "#id-name";
Then based on if mySelector holds a Class or ID I would run
document.getElementsByClassName
or
document.getElementsById
What would be the best way to do this without the use of a library like jQuery or another library?

Take a look at document.querySelector or document.querySelectorAll, instead. Both of those can find elements by ID or class (as well as other selectors). querySelector will return 1 element, querySelectorAll will return all elements.
var mySelector = ".class-name", // "#id-name" will also work fine.
elements = document.querySelectorAll(mySelector);
Note that this doesn't work in IE < 8 (see http://caniuse.com/#search=querySelectorAll). A polyfill would be the best way to handle it to add IE7 support.

You can use this simple if/else statement to differentiate. This would also allow you to run other code based on whether it's a class or an ID you are referencing.
var mySelector = ".class-name";
if(mySelector.charAt(0) == ".")
{
document.getElementsByClassName(mySelector.substring(1));
}
else if(mySelector.charAt(0) == "#")
{
document.getElementsById(mySelector.substring(1));
}

The first way I think is check a first symbol of stroke.
Something like:
var $ = function( string ) {
var result;
switch (string.substr(0,1)) {
case '.': result = document.getElementsByClassName(string); break;
case '#': result = document.getElementById(string); break;
default: result = document.getElementsByTagName(string); break;
}
return result;
}
var mySelector = ".class-name";
console.log( $(mySelector) );

Just because you only want a selector and not the entire jQuery library, doesn't mean you have to roll your own own. jQuery uses the Sizzle selector engine, and you could just as easily use it yourself without the overhead of full jQuery:
http://sizzlejs.com/

I'm not an advanced user, but some time ago I created this little script:
https://gist.github.com/caiotarifa/cc7d486292f39157d763
var __;
__ = function(selector, filter) {
'use strict';
var response;
function filtering(selectors, filter) {
switch (filter) {
case "first":
return selectors[0];
break;
case "last":
return selectors[selectors.length - 1];
break;
default:
return selectors[filter];
break;
}
}
selector = selector.trim();
if (typeof filter === "string") { filter = filter.trim(); }
if (selector.indexOf(' ') < 0 && selector.indexOf('.', 1) < 0 && selector.indexOf('#', 1) < 0) {
switch (selector.substr(0, 1)) {
case '.':
response = document.getElementsByClassName(selector.substr(1));
if (response.length === 1) { filter = "first"; }
if (typeof filter !== "undefined") { response = filtering(response, filter) }
break;
case '#':
response = document.getElementById(selector.substr(1));
break;
default:
response = document.getElementsByTagName(selector);
if (response.length === 1) { filter = "first"; }
if (typeof filter !== "undefined") { response = filtering(response, filter) }
break;
}
} else {
if (typeof filter !== "undefined") {
switch (filter) {
case "first":
response = document.querySelector(selector);
break;
case "last":
response = document.querySelectorAll(selector);
response = response[response.length - 1];
break;
default:
response = document.querySelectorAll(selector);
response = response[filter];
break;
}
} else {
response = document.querySelectorAll(selector);
if (response.length === 1) { response = response[0]; }
else if (response.length < 1) { response = false; }
}
}
return response;
};
It's simple to use it:
__("div")
Or passing some filter like:
__("div", "first")
I didn't make a benchmark test with it. I hope it can help you.

Related

Using switch case in javascript

This is the variable i am having right now
[
{
"_id":"63773059c3160f782c087e33",
"nfrid":"637328ebf5c4b2558b064809",
"nfrname":"azuread",
"fileName":"package.json",
"isImport":false,
"isConst":false,
"isComponent":false,
"isNewFile":false,
"landmark":"\"react\"",
"isAfter":false,
"fileContent":"\"#azure/msal-react\": \"^1.4.9\",",
"filePath":"package.json",
"isPackage":true,
"isIndexHtml":false,
"projecttypeid":"6372366d1b568e00d8af2e44",
"projecttypetitle":"PWA React",
"nfrGitIo":[
{
"_id":"637328ebf5c4b2558b064809",
"iconpath":"https://cdnerapidxdevportal.azureedge.net/webdesignerimages/azure-active-directory-aad-icon-488x512-3d71nrtk.png",
"title":"Azure AD",
"description":"Azure Active Directory (Azure AD), part of Microsoft Entra, is an enterprise identity service that provides single sign-on, multifactor authentication, and conditional access to guard against 99.9 percent of cybersecurity attacks."
}
]
},
{
"_id":"63773144c3160f782c087e35",
"nfrid":"637328ebf5c4b2558b064809",
"nfrname":"azuread",
"fileName":"index.js",
"isImport":true,
"isConst":false,
"isComponent":false,
"isNewFile":false,
"isPackage":false,
"landmark":null,
"isAfter":null,
"fileContent":"import { MsalProvider } from '#azure/msal-react';import { msalConfig } from './authConfig';import {PublicClientApplication } from '#azure/msal-browser';",
"filePath":"src/index.js",
"isIndexHtml":false,
"projecttypeid":"6372366d1b568e00d8af2e44",
"projecttypetitle":"PWA React",
"nfrGitIo":[
{
"_id":"637328ebf5c4b2558b064809",
"iconpath":"https://cdnerapidxdevportal.azureedge.net/webdesignerimages/azure-active-directory-aad-icon-488x512-3d71nrtk.png",
"title":"Azure AD",
"description":"Azure Active Directory (Azure AD), part of Microsoft Entra, is an enterprise identity service that provides single sign-on, multifactor authentication, and conditional access to guard against 99.9 percent of cybersecurity attacks."
}
]
},
]
I am having many flags like isImport, isPackage, isIndexHtml like that. I am trying to put those flags in a switch case and call individual function when each flag is true.Something like this,
for (let i = 0; i < cosmos.length; i++) {
console.log(cosmos[0].isPackage);
switch (cosmos[i]) {
case `${cosmos[i].isImport === true}`:
const statusImport = common.updateImport(cosmos[i]);
console.log(statusImport);
break;
// case `${cosmos[i].isConst === true}`:
// console.log("I own a dog");
// break;
case `${cosmos[i].isPackage === true}`:
const statusPackage = common.updatePackage(cosmos[i]);
console.log(statusPackage);
break;
case `${cosmos[i].isIndexHtml === true}`:
const statusIndexHtml = common.updateIndexHTML(cosmos[i]);
console.log(statusIndexHtml);
break;
// case `${cosmos[i].isNewFile === true}`:
// const statusNewFile = common.addNewFile(cosmos[i]);
// console.log(statusNewFile);
// break;
default:
console.log("Nothing to add/update");
break;
}
}
But when I run this i am always getting the default console log. I dont know what i am missing
This is my first switch case implementation. Can someone point me in the right direction?
Don't convert them to strings and in switch condition add just true:
for (let i = 0; i < cosmos.length; i++) {
console.log(cosmos[0].isPackage);
switch (true) {
case cosmos[i].isImport:
const statusImport = common.updateImport(cosmos[i]);
console.log(statusImport);
break;
case cosmos[i].isPackage:
const statusPackage = common.updatePackage(cosmos[i]);
console.log(statusPackage);
break;
case cosmos[i].isIndexHtml:
const statusIndexHtml = common.updateIndexHTML(cosmos[i]);
console.log(statusIndexHtml);
break;
default:
console.log("Nothing to add/update");
break;
}
}
switch is not the right construct to use in this case.
Simply use if/else here.
Since you're testing several different values from cosmos[i], not testing a single value against multiple possible matches, switch isn't the right tool here. (You can use it, just like you can use a wrench to bang in a nail, but it's not the right tool.) Instead, use an if/else if/else chain:
for (let i = 0; i < cosmos.length; i++) {
if (cosmos[i].isImport) {
const statusImport = common.updateImport(cosmos[i]);
console.log(statusImport);
} else if (cosmos[i].isPackage) {
const statusPackage = common.updatePackage(cosmos[i]);
console.log(statusPackage);
} else if (cosmos[i].isIndexHtml) {
const statusIndexHtml = common.updateIndexHTML(cosmos[i]);
console.log(statusIndexHtml);
} else {
console.log("Nothing to add/update");
}
}
Separately, in new code, I'd suggest using a for-of instead of a for when you don't need the index:
for (const entry of cosmos) {
if (entry.isImport) {
const statusImport = common.updateImport(entry);
console.log(statusImport);
} else if (entry.isPackage) {
const statusPackage = common.updatePackage(entry);
console.log(statusPackage);
} else if (entry.isIndexHtml) {
const statusIndexHtml = common.updateIndexHTML(entry);
console.log(statusIndexHtml);
} else {
console.log("Nothing to add/update");
}
}
A switch statement can only interrogate one variable. In your case the correct solution is an if statement for each member variable. Replace the switch statement with this snippet:
if (cosmos[i].isImport === true) {
const statusImport = common.updateImport(cosmos[i]);
console.log(statusImport);
}
if (cosmos[i].isPackage === true) {
const statusPackage = common.updatePackage(cosmos[i]);
console.log(statusPackage);
}
if (cosmos[i].isIndexHtml === true) {
const statusIndexHtml = common.updateIndexHTML(cosmos[i]);
console.log(statusIndexHtml);
}
I note that your data structure does not mutually exclude the isImport isPackage and isIndexHtml - so in principle any combination of them could be true and my proposed code would execute accordingly.

Find and replace text in whole DOM

I am making a chrome extension to find a string if text in DOM and replace it with something else.
What is the best way to traverse the whole DOM element wise and replace the text in DOM. I Thought of placing document.body in a variable and then process it as a qeue but I am confused that how to do so
This is my Code:
flag = true;
var word = 'word',//word to replace
queue = [document.body],
curr;
try {
while ((curr = queue.pop()) || flag) {
if (!(curr.textContent.match(word))
continue;
for (var i = 0; i < curr.childNodes.length; ++i) {
if (!flag) break;
switch (curr.childNodes[i].nodeType) {
case Node.TEXT_NODE: // 3
if (curr.childNodes[i].textContent.match(word)) {
curr.childNodes[i].textContent("xxx");//replacing the word
console.log('Found!');
flag = false;
break;
}
break;
case Node.ELEMENT_NODE: // 1
queue.push(curr.childNodes[i]);
break;
}
}
}
} catch (e) {
//
}
you can do it I think with
function replaceAll(recherche, remplacement, chaineAModifier)
{
return chaineAModifier.split(recherche).join(remplacement);
}
str = $('body').html()
replaceAll(search_word,replacement,str)
$('body').html(str)
but that will replace everything including html nodes attribute and name

Chrome Extension - sendRequest slow

I am having trouble getting my content script request values from my background script.
content_script.js
=================
var elements = undefined
var properties = undefined
var targets = undefined
chrome.extension.sendRequest({greeting: "elements"}, function(response) {
elements = response.input;
});
if (elements == undefined){
var elements = ["a","img"];
}else{
elements = elements.split(',');
}
chrome.extension.sendRequest({greeting: "properties"}, function(response) {
properties = response.input;
});
if (properties == undefined){
var properties = ["alt","id","class"];
}else{
properties = properties.split(',');
}
chrome.extension.sendRequest({greeting: "targets"}, function(response) {
targets = response.input;
});
if (targets == undefined){
var targets = ["onclick","href"];
}else{
targets = targets.split(',');
}...
...More code and references to elements following...
The above code only works when there is a break in the code (ie waiting) before doing any relating to the values set above, I suppose I could put something to do that but i would prefer to use a more efficient solution if possible.
(for reference:)
background.js
=============
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
switch (request.greeting){
case "elements":
var elements = localStorage["elements"];
sendResponse({input: elements});
break;
case "properties":
var properties = localStorage["properties"];
sendResponse({input: properties});
break;
case "targets":
var targets = localStorage["targets"];
sendResponse({input: targets});
break;
}
});
I have been at this for 3 hours (still learning what I'm doing with JS)
Uhhhhhm you cannot do that:
chrome.extension.sendRequest({greeting: "properties"}, function(response) {
properties = response.input;
});
if (properties == undefined){ // always undefined
var properties = ["alt","id","class"];
}else{
properties = properties.split(',');
}
sendRequest is async.
And the correct way of checking for undefined is:
if (typeof properties == "undefined")
If you need all that stuff just make 1 request and do all your stuff inside the callback:
chrome.extension.sendRequest({greeting: "all"}, function(response) {
if (response.elements === null) {
var elements = ["a","img"];
} else {
var elements = response.elements.split(',');
}
if (response.properties === null) {
var properties = ["alt","id","class"];
} else {
var properties = response.properties.split(',');
}
if (response.targets === null) {
var targets = ["onclick","href"];
} else {
var targets = response.targets.split(',');
}
});
And in background:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
switch (request.greeting){
case "all":
sendResponse({
elements: localStorage.getItem("targets"),
properties: localStorage.getItem("properties"),
targets: localStorage.getItem("targets")
});
break;
}
});

Using getNext() with Mootools

I'm trying to do an autocompleter in mootools 1.11. Everything works fine but i just cant check if
this.selectel.getNext()
is null or whatever. Firebug outputs [li] for every element and [null] for the non existing element i output via getNext();
I saw that some people are just doing:
if(this.selectel.getNext()) {...
but thats not working here because i always get the null object. Something terribly stupid must be going on here...
Here comes some code around the problem:
this.selectel = $$('ul.results').getFirst();
...
onCommand: function(e, mouse) {
if (e.key && !e.shift) {
switch (e.key) {
case 'up':
this.selectel.getPrevious().addClass('active');
if(this.selectel) this.selectel.removeClass('active');
this.selectel = this.selectel.getPrevious();
e.stop();
return;
case 'down':
var test = this.selectel.getNext();
console.log(typeof(test));
if(this.selectel.getNext() != null) { // not working
this.selectel.getNext().addClass('active');
if(this.selectel) this.selectel.removeClass('active');
this.selectel = this.selectel.getNext();
}
e.stop();
return;
}
}
your are calling getNext() twice.
replace these lines:
if(this.selectel.getNext() != null) { // not working
this.selectel.getNext().addClass('active');
if(this.selectel) this.selectel.removeClass('active');
this.selectel = this.selectel.getNext();
}
with:
if(el = this.selectel.getNext() != null) { // not working
el.addClass('active');
if(this.selectel) this.selectel.removeClass('active');
this.selectel = el;
}

Javascript for conditional URL append or redirect based on window.location.href

I am trying to make a bookmarklet that when clicked will check the URL of the current tab/window to see if it contains 'char1' and/or 'char2' (a given character). If both chars are present it redirects to another URL, for the other two it will append the current URL respectively.
I believe there must be a more elegant way of stating this than the following (which has so far worked perfectly for me) but I don't have great knowledge of Javascript. My (unwieldy & repetitive) working code (apologies):
if (window.location.href.indexOf('char1') != -1 &&
window.location.href.indexOf('char2') != -1)
{
window.location="https://website.com/";
}
else if (window.location.href.indexOf('char1') != -1)
{
window.location.assign(window.location.href += 'append1');
}
else if (window.location.href.indexOf('char2') != -1)
{
window.location.assign(window.location.href += 'append2');
}
Does exactly what I need it to but, well... not very graceful to say the least.
Is there a simpler way to do this, perhaps with vars or a pseudo-object? Or better code?
A (sort-of) refactoring of dthorpe's suggestion:
var hasC1 = window.location.href.indexOf('char1')!=-1
var hasC2 = window.location.href.indexOf('char2')!=-1
var newLoc = hasC1
? hasC2 ? "https://website.com/" : window.location.href+'append1'
: hasC2 ? window.location.href+'append1' : '';
if (newLoc)
window.location = newLoc;
Calling assign is the same as assigning a value to window.location, you were doing both with the addition assignment += operator in the method anyway:
window.location.assign(window.location.href+='append2')
This would actually assign "append2" to the end of window.location.href before calling the assign method, making it redundant.
You could also reduce DOM lookups by setting window.location to a var.
The only reduction I can see is to pull out the redundant indexof calls into vars and then test the vars. It's not going to make any appreciable difference in performance though.
var hasChar1 = window.location.href.indexOf('char1') != -1;
var hasChar2 = window.location.href.indexOf('char2') != -1;
if (hasChar1)
{
if (hasChar2)
{
window.location="https://website.com/";
}
else
{
window.location.assign(window.location.href+='append1');
}
}
else if (hasChar2)
{
window.location.assign(window.location.href+='append2');
}
Kind of extendable code. Am i crazy?
var loc = window.location.href;
var arr = [{
url: "https://website.com/",
chars: ["char1", "char2"]
}, {
url: loc + "append1",
chars: ["char1"]
}, {
url: loc + "append2",
chars: ["char2"]
}];
function containsChars(str, chars)
{
var contains = true;
for(index in chars) {
if(str.indexOf(chars[index]) == -1) {
contains = false;
break;
}
}
return contains;
}
for(index in arr) {
var item = arr[index];
if(containsChars(loc, item.chars)) {
window.location.href = item.url;
break;
}
}
var location =window.location.href
if (location.indexOf('char1')!=-1 && location.indexOf('char2')!=-1)
{window.location="https://website.com/";}
else if (location.href.indexOf('char1')!=-1) {window.location.assign(location+='append1');}
else if (location.indexOf('char2')!=-1) {window.location.assign(location+='append2');}

Categories

Resources