1670094900
CSS classes are very helpful when need to add same style on multiple HTML elements.
Sometimes need to perform an action based on a class element has.
In this tutorial, I show how you can check if element has a specific class using JavaScript with examples.
HTML
<div id='divel' >
and added class red
to it.hasClass()
function. Pass <div >
instance and class name that needs to check.red
class on <div id='divel' >
.<div id='result1'></div>
using JavaScript.JavaScript
hasClass()
function.classList.contains()
to search on element. It returns a boolean value.true
then display True
message to <div id='result1'>
otherwise, display False
message.Completed
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How to Check if element has class in JavaScript</title>
</head>
<body>
<style>
.content{
width: 100px;
height: 100px;
color: white;
}
.red{
background: red;
}
</style>
<h2>Search class on single element</h2>
<div class='content red' id='divel' ></div>
<br><br>
<input type='button' value="Has class - red" onclick="hasClass(document.getElementById('divel'),'red')">
<br><br>
<b>Result : </b><br>
<div id='result1'></div>
<!-- Script -->
<script type="text/javascript">
// Single search
function hasClass(el,classname){
if(el.classList.contains(classname)){
document.getElementById('result1').innerHTML = 'True';
}else{
document.getElementById('result1').innerHTML = 'False';
}
}
</script>
</body>
</html>
HTML
Created 3 <div class='content' >
elements. 2 <div >
has red
class and 1 has blue
class. 1 button to search red
class.
Display <div >
ids that has red
class in <div id='result2'>
.
JavaScript
Create 2 functions –
This function takes 2 parameters – element instance and search class name. Search classname
using classList.contains()
and return true
and false
.
<div >
ids that has red
class.This function calls on button click. This function takes 1 parameter – search class name. Loop on <div >
that has class name content. Pass <div >
instance and classname
variable in hasClass()
function.
If it returns true
then read <div >
id
attribute and append in ids
variable.
Display <div >
ids in <div id='result2'>
.
Completed Code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How to Check if element has class in JavaScript</title>
</head>
<body>
<style>
.content{
width: 100px;
height: 100px;
display: inline-block;
color: white;
}
.red{
background: red;
}
.blue{
background: blue;
}
</style>
<h2>Search class on multiple elements</h2>
<div class='content red' id='div1'>div1</div>
<div class='content blue' id='div2'>div2</div>
<div class='content red' id='div3'>div3</div><br><br>
<input type='button' value="Has class - red" id='check' onclick="checkClass('red');">
<br><br>
<b>Result</b><br><br>
<div id='result2'></div>
<script type="text/javascript">
// Search class
function hasClass(el,classname){
if(el.classList.contains(classname)){
return true;
}else{
return false;
}
}
// Multiple search
function checkClass(classname){
var div = document.getElementsByClassName('content');
var totalel = div.length;
var ids = "";
for(var i=0;i<totalel;i++){
if(hasClass(div[i],classname)){
var divid = div[i].getAttribute('id');
ids += divid + ", ";
}
document.getElementById('result2').innerHTML = ids;
}
}
</script>
</body>
</html>
I hope using the examples you have successfully implemented class searching using JavaScript.
You can view this tutorial to know class searching using jQuery.
If you found this tutorial helpful then don't forget to share.
Original article source at: https://makitweb.com/
1662107520
Superdom
You have dom
. It has all the DOM virtually within it. Use that power:
// Fetch all the page links
let links = dom.a.href;
// Links open in a new tab
dom.a.target = '_blank';
Only for modern browsers
Simply use the CDN via unpkg.com:
<script src="https://unpkg.com/superdom@1"></script>
Or use npm or bower:
npm|bower install superdom --save
It always returns an array with the matched elements. Get all the elements that match the selector:
// Simple element selector into an array
let allLinks = dom.a;
// Loop straight on the selection
dom.a.forEach(link => { ... });
// Combined selector
let importantLinks = dom['a.important'];
There are also some predetermined elements, such as id
, class
and attr
:
// Select HTML Elements by id:
let main = dom.id.main;
// by class:
let buttons = dom.class.button;
// or by attribute:
let targeted = dom.attr.target;
let targeted = dom.attr['target="_blank"'];
Use it as a function or a tagged template literal to generate DOM fragments:
// Not a typo; tagged template literals
let link = dom`<a href="https://google.com/">Google</a>`;
// It is the same as
let link = dom('<a href="https://google.com/">Google</a>');
Delete a piece of the DOM
// Delete all of the elements with the class .google
delete dom.class.google; // Is this an ad-block rule?
You can easily manipulate attributes right from the dom
node. There are some aliases that share the syntax of the attributes such as html
and text
(aliases for innerHTML
and textContent
). There are others that travel through the dom such as parent
(alias for parentNode) and children
. Finally, class
behaves differently as explained below.
The fetching will always return an array with the element for each of the matched nodes (or undefined if not there):
// Retrieve all the urls from the page
let urls = dom.a.href; // #attr-list
// ['https://google.com', 'https://facebook.com/', ...]
// Get an array of the h2 contents (alias of innerHTML)
let h2s = dom.h2.html; // #attr-alias
// ['Level 2 header', 'Another level 2 header', ...]
// Get whether any of the attributes has the value "_blank"
let hasBlank = dom.class.cta.target._blank; // #attr-value
// true/false
You also use these:
innerHTML
): retrieve a list of the htmlstextContent
): retrieve a list of the htmlsparentNode
): travel up one level// Set target="_blank" to all links
dom.a.target = '_blank'; // #attr-set
dom.class.tableofcontents.html = `
<ul class="tableofcontents">
${dom.h2.map(h2 => `
<li>
<a href="#${h2.id}">
${h2.innerHTML}
</a>
</li>
`).join('')}
</ul>
`;
To delete an attribute use the delete
keyword:
// Remove all urls from the page
delete dom.a.href;
// Remove all ids
delete dom.a.id;
It provides an easy way to manipulate the classes.
To retrieve whether a particular class is present or not:
// Get an array with true/false for a single class
let isTest = dom.a.class.test; // #class-one
For a general method to retrieve all classes you can do:
// Get a list of the classes of each matched element
let arrays = dom.a.class; // #class-arrays
// [['important'], ['button', 'cta'], ...]
// If you want a plain list with all of the classes:
let flatten = dom.a.class._flat; // #class-flat
// ['important', 'button', 'cta', ...]
// And if you just want an string with space-separated classes:
let text = dom.a.class._text; // #class-text
// 'important button cta ...'
// Add the class 'test' (different ways)
dom.a.class.test = true; // #class-make-true
dom.a.class = 'test'; // #class-push
// Remove the class 'test'
dom.a.class.test = false; // #class-make-false
Did we say it returns a simple array?
dom.a.forEach(link => link.innerHTML = 'I am a link');
But what an interesting array it is; indeed we are also proxy'ing it so you can manipulate its sub-elements straight from the selector:
// Replace all of the link's html with 'I am a link'
dom.a.html = 'I am a link';
Of course we might want to manipulate them dynamically depending on the current value. Just pass it a function:
// Append ' ^_^' to all of the links in the page
dom.a.html = html => html + ' ^_^';
// Same as this:
dom.a.forEach(link => link.innerHTML = link.innerHTML + ' ^_^');
Note: this won't work
dom.a.html += ' ^_^';
for more than 1 match (for reasons)
Or get into genetics to manipulate the attributes:
dom.a.attr.target = '_blank';
// Only to external sites:
let isOwnPage = el => /^https?\:\/\/mypage\.com/.test(el.getAttribute('href'));
dom.a.attr.target = (prev, i, element) => isOwnPage(element) ? '' : '_blank';
You can also handle and trigger events:
// Handle click events for all <a>
dom.a.on.click = e => ...;
// Trigger click event for all <a>
dom.a.trigger.click;
We are using Jest as a Grunt task for testing. Install Jest and run in the terminal:
grunt watch
Author: franciscop
Source Code: https://github.com/franciscop/superdom
License: MIT license
1684207573
Different types of files are used in Bash for different purposes. Many options are available in Bash to check if the particular file exists or not. The existence of the file can be checked using the file test operators with the “test” command or without the “test” command. The purposes of different types of file test operators to check the existence of the file are shown in this tutorial.
Many file test operators exist in Bash to check if a particular file exists or not. Some of them are mentioned in the following:
Operator | Purpose |
-f | It is used to check if the file exists and if it is a regular file. |
-d | It is used to check if the file exists as a directory. |
-e | It is used to check the existence of the file only. |
-h or -L | It is used to check if the file exists as a symbolic link. |
-r | It is used to check if the file exists as a readable file. |
-w | It is used to check if the file exists as a writable file. |
-x | It is used to check if the file exists as an executable file. |
-s | It is used to check if the file exists and if the file is nonzero. |
-b | It is used to check if the file exists as a block special file. |
-c | It is used to check if the file exists as a special character file. |
Many ways of checking the existence of the regular file are shown in this part of the tutorial.
Create a Bash file with the following script that takes the filename from the user and check whether the file exists in the current location or not using the -f operator in the “if” condition with the single third brackets ([]).
#!/bin/bash
#Take the filename
echo -n "Enter the filename: "
read filename
#Check whether the file exists or not using the -f operator
if [ -f "$filename" ]; then
echo "File exists."
else
echo "File does not exist."
fi
The script is executed twice in the following script. The non-existence filename is given in the first execution. The existing filename is given in the second execution. The “ls” command is executed to check whether the file exists or not.
Create a Bash file with the following script that takes the filename as a command-line argument and check whether the file exists in the current location or not using the -f operator in the “if” condition with the double third brackets ([[ ]]).
#!/bin/bash
#Take the filename from the command-line argument
filename=$1
#Check whether the argument is missing or not
if [ "$filename" != "" ]; then
#Check whether the file exists or not using the -f operator
if [[ -f "$filename" ]]; then
echo "File exists."
else
echo "File does not exist."
fi
else
echo "Argument is missing."
fi
The script is executed twice in the following script. No argument is given in the first execution. An existing filename is given as an argument in the second execution. The “ls” command is executed to check whether the file exists or not.
Create a Bash file with the following script that takes the filename as a command-line argument and check whether the file exists in the current location or not using the -f operator with the “test” command in the “if” condition.
#!/bin/bash
#Take the filename from the command-line argument
filename=$1
#Check whether the argument is missing or not
if [ $# -lt 1 ]; then
echo "No argument is given."
exit 1
fi
#Check whether the file exists or not using the -f operator
if test -f "$filename"; then
echo "File exists."
else
echo "File does not exist."
fi
The script is executed twice in the following script. No argument is given in the first execution. An existing filename is given in the second execution.
Create a Bash file with the following script that checks whether the file path exists or not using the -f operator with the “test” command in the “if” condition.
#!/bin/bash
#Set the filename with the directory location
filename='temp/courses.txt'
#Check whether the file exists or not using the -f operator
if test -f "$filename"; then
echo "File exists."
else
echo "File does not exist."
fi
The following output appears after executing the script:
The methods of checking whether a regular file exists or not in the current location or the particular location are shown in this tutorial using multiple examples.
Original article source at: https://linuxhint.com/
1684215440
Различные типы файлов используются в Bash для разных целей. В Bash доступно множество опций, позволяющих проверить, существует ли конкретный файл или нет. Существование файла можно проверить с помощью операторов проверки файлов с командой «test» или без команды «test». В этом руководстве показаны цели различных типов операторов проверки файлов для проверки существования файла.
В Bash существует множество операторов проверки файлов, чтобы проверить, существует ли конкретный файл или нет. Некоторые из них упоминаются в следующем:
Оператор | Цель |
-f | Он используется для проверки того, существует ли файл и является ли он обычным файлом. |
-д | Он используется для проверки существования файла в виде каталога. |
-е | Он используется только для проверки существования файла. |
-ч или -л | Он используется для проверки существования файла в виде символической ссылки. |
-р | Он используется для проверки того, существует ли файл как читаемый файл. |
-w | Он используется для проверки того, существует ли файл как файл, доступный для записи. |
-Икс | Он используется для проверки того, существует ли файл как исполняемый файл. |
-с | Он используется для проверки того, существует ли файл и не равен ли он нулю. |
-б | Он используется для проверки того, существует ли файл в виде специального блочного файла. |
-с | Он используется для проверки того, существует ли файл как файл со специальными символами. |
В этой части руководства показано множество способов проверки существования обычного файла.
Создайте файл Bash со следующим сценарием, который берет имя файла от пользователя и проверяет, существует ли файл в текущем местоположении или нет, используя оператор -f в условии «если» с одной третьей скобкой ([]).
#!/bin/bash
#Take the filename
echo -n "Enter the filename: "
read filename
#Check whether the file exists or not using the -f operator
if [ -f "$filename" ]; then
echo "File exists."
else
echo "File does not exist."
fi
Сценарий выполняется дважды в следующем сценарии. Несуществующее имя файла дается при первом выполнении. Существующее имя файла дается во втором исполнении. Команда «ls» выполняется, чтобы проверить, существует ли файл или нет.
Создайте файл Bash со следующим сценарием, который принимает имя файла в качестве аргумента командной строки и проверяет, существует ли файл в текущем местоположении или нет, используя оператор -f в условии «если» с двойными третьими скобками ([[] ]).
#!/bin/bash
#Take the filename from the command-line argument
filename=$1
#Check whether the argument is missing or not
if [ "$filename" != "" ]; then
#Check whether the file exists or not using the -f operator
if [[ -f "$filename" ]]; then
echo "File exists."
else
echo "File does not exist."
fi
else
echo "Argument is missing."
fi
Сценарий выполняется дважды в следующем сценарии. При первом выполнении аргумент не передается. Существующее имя файла задается в качестве аргумента при втором выполнении. Команда «ls» выполняется, чтобы проверить, существует ли файл или нет.
Создайте файл Bash со следующим сценарием, который принимает имя файла в качестве аргумента командной строки и проверяет, существует ли файл в текущем местоположении или нет, используя оператор -f с командой «test» в условии «if».
#!/bin/bash
#Take the filename from the command-line argument
filename=$1
#Check whether the argument is missing or not
if [ $# -lt 1 ]; then
echo "No argument is given."
exit 1
fi
#Check whether the file exists or not using the -f operator
if test -f "$filename"; then
echo "File exists."
else
echo "File does not exist."
fi
Сценарий выполняется дважды в следующем сценарии. При первом выполнении аргумент не передается. Существующее имя файла дается во втором исполнении.
Создайте файл Bash со следующим скриптом, который проверяет, существует ли путь к файлу или нет, используя оператор -f с командой «test» в условии «if».
#!/bin/bash
#Set the filename with the directory location
filename='temp/courses.txt'
#Check whether the file exists or not using the -f operator
if test -f "$filename"; then
echo "File exists."
else
echo "File does not exist."
fi
После выполнения скрипта появляется следующий вывод:
Методы проверки того, существует ли обычный файл в текущем местоположении или в конкретном месте, показаны в этом руководстве с использованием нескольких примеров.
Оригинальный источник статьи: https://linuxhint.com/
1684211760
Bash 中出于不同的目的使用不同类型的文件。Bash 中有许多选项可用于检查特定文件是否存在。可以使用带有“test”命令或不带有“test”命令的文件测试操作符来检查文件是否存在。本教程显示了不同类型的文件测试操作符检查文件是否存在的目的。
Bash 中存在许多文件测试运算符来检查特定文件是否存在。下面提到了其中一些:
操作员 | 目的 |
-F | 它用于检查文件是否存在以及它是否是常规文件。 |
-d | 它用于检查文件是否作为目录存在。 |
-e | 它仅用于检查文件是否存在。 |
-h 或 -L | 它用于检查文件是否作为符号链接存在。 |
-r | 它用于检查文件是否作为可读文件存在。 |
-w | 它用于检查文件是否作为可写文件存在。 |
-X | 它用于检查文件是否作为可执行文件存在。 |
-s | 它用于检查文件是否存在以及文件是否为非零。 |
-b | 它用于检查文件是否作为块特殊文件存在。 |
-C | 它用于检查文件是否作为特殊字符文件存在。 |
本教程的这一部分显示了许多检查常规文件是否存在的方法。
使用以下脚本创建一个 Bash 文件,该脚本从用户那里获取文件名,并在“if”条件中使用带有第三个括号 ([]) 的 -f 运算符检查文件是否存在于当前位置。
#!/bin/bash
#Take the filename
echo -n "Enter the filename: "
read filename
#Check whether the file exists or not using the -f operator
if [ -f "$filename" ]; then
echo "File exists."
else
echo "File does not exist."
fi
该脚本在以下脚本中执行了两次。不存在的文件名在第一次执行时给出。现有文件名在第二次执行时给出。执行“ls”命令来检查文件是否存在。
使用以下脚本创建一个 Bash 文件,该脚本将文件名作为命令行参数,并在“if”条件中使用 -f 运算符和双第三括号 ([[ ] ]).
#!/bin/bash
#Take the filename from the command-line argument
filename=$1
#Check whether the argument is missing or not
if [ "$filename" != "" ]; then
#Check whether the file exists or not using the -f operator
if [[ -f "$filename" ]]; then
echo "File exists."
else
echo "File does not exist."
fi
else
echo "Argument is missing."
fi
该脚本在以下脚本中执行了两次。第一次执行时不给出参数。在第二次执行中,将现有文件名作为参数给出。执行“ls”命令来检查文件是否存在。
使用以下将文件名作为命令行参数的脚本创建 Bash 文件,并在“if”条件下使用 -f 运算符和“test”命令检查文件是否存在于当前位置。
#!/bin/bash
#Take the filename from the command-line argument
filename=$1
#Check whether the argument is missing or not
if [ $# -lt 1 ]; then
echo "No argument is given."
exit 1
fi
#Check whether the file exists or not using the -f operator
if test -f "$filename"; then
echo "File exists."
else
echo "File does not exist."
fi
该脚本在以下脚本中执行了两次。第一次执行时不给出参数。第二次执行时给出一个现有的文件名。
使用以下脚本创建 Bash 文件,在“if”条件下使用 -f 运算符和“test”命令检查文件路径是否存在。
#!/bin/bash
#Set the filename with the directory location
filename='temp/courses.txt'
#Check whether the file exists or not using the -f operator
if test -f "$filename"; then
echo "File exists."
else
echo "File does not exist."
fi
执行脚本后出现如下输出:
本教程通过多个示例展示了检查当前位置或特定位置是否存在常规文件的方法。
文章原文出处:https: //linuxhint.com/
1684202959
It is essential to count the total number of arguments that are passed to the script for various purposes such as error handling, providing messages based on the number of arguments, and helping the user to pass the correct number of arguments. The total number of arguments can be counted in Bash in two ways. One is using “$#” and another by using a loop. The methods of checking the number of arguments and using this value for different purposes are shown in this tutorial.
The uses of checking the number of arguments are shown in this part of the tutorial using multiple examples.
Create a Bash file with the following script that counts the total number of arguments and print the argument values using a “for” loop.
#!/bin/bash
#Store the number of arguments
len=$#
echo "Total number of arguments: $len"
echo "Argument values are:"
#Print the argument values
for val in $@
do
echo $val
done
The following output appears after executing the script with the argument values of 67, 34, and 12:
Create a Bash file with the following script that counts the total number of arguments and print the argument values based on the number of arguments. An error message is printed if no argument is passed to the script.
#!/bin/bash
#Store the number of arguments
len=$#
#check the total number of arguments
if [ $len -eq 0 ]; then
echo "No argument is given"
fi
#initialize the counter
counter=0
#Print argument value based on the counter value
while (( $counter < $len ))
do
if [ $counter -lt 1 ]; then
echo $1
elif [ $counter -lt 2 ]; then
echo $2
elif [ $counter -lt 3 ]; then
echo $3
fi
((counter++))
done
The script is executed four times in the output. The error message is printed when no argument is given. The argument values are printed when one, two, and three argument values are given.
Create a Bash file with the following script that counts the total number of arguments and print the average value of five argument values. The “bc” command is used in the script to calculate the average value. An error message is printed if no argument is passed to the script.
#!/bin/bash
#Check the total number of arguments
if [ $# -eq 5 ]; then
#Calculate the sum of the argument values
sum=$(($1+$2+$3+$4+$5))
#Calculate the average values
avg=$(($sum/5 | bc -l))
#Print the average values and the argument values
echo "Arguments values are: $1 $2 $3 $4 $5"
echo "Average value: $avg"
else
#Print error message
echo "Total number of arguments must be 5."
fi
The script is executed twice in the output. The error message is printed when no argument is given. The average of the argument values are printed when five argument values are given.
Create a Bash file with the following script that prints any of the three messages based on the “if” condition. The first “if” condition checks whether the number of arguments is 2 or not. The second “if” condition checks whether the length of the argument value is less than 5 or not. The third “if” condition checks whether the second argument is positive or not.
#!/bin/bash
#Read the argument values
name=$1
price=$2
#Count the length of the second argument
len=${#name}
#Check the total number of arguments
if [ $# -ne 2 ]; then
echo "Total number of arguments must be 2."
exit
#Check the length of the first argument
elif [ $len -lt 5 ]; then
echo "Product name must be minimum 5 characters long."
exit
#Check the value of the second argument
elif [ $2 -lt 0 ]; then
echo "The price value must be positive."
exit
fi
#Print the argument values
echo "The price of $name is TK. $price"
The script is executed four times in the output. The error message, “Total number of arguments must be 2”, is printed when no argument is given. The error message, “Product name must be minimum 5 characters long”, is printed when the length of the first argument is less than five. The error message, “The price value must be positive”, is printed when the second argument is negative.
The uses of the number of arguments in the Bash script for various purposes are shown in this tutorial using multiple examples to help the new Bash users.
Original article source at: https://linuxhint.com/