Gordon  Murray

Gordon Murray

1670094900

Check If Element Has Class in JavaScript

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.

Contents

  1. Check class on a single element using JavaScript
  2. Check class on multiple elements using JavaScript
  3. Conclusion

1. Check class on a single element using JavaScript

HTML

  • Create a <div id='divel' > and added class red to it.
  • Create a button that calls hasClass() function. Pass <div > instance and class name that needs to check.
  • In example, I am checking red class on <div id='divel' >.
  • Display class status in <div id='result1'></div> using JavaScript.

JavaScript

  • Create hasClass() function.
  • It takes 2 parameters –
    • Element instance in which search class.
    • Class name that needs to find.
  • Use classList.contains() to search on element. It returns a boolean value.
  • If its return 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>

 

View Demo


2. Check class on multiple elements using JavaScript

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 –

  • hasClass() –

This function takes 2 parameters – element instance and search class name. Search classname using classList.contains() and return true and false.

  • checkClass() – Using this function display <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>

View Demo


3. Conclusion

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/

#javascript #class 

What is GEEK

Buddha Community

Check If Element Has Class in JavaScript
Lawrence  Lesch

Lawrence Lesch

1662107520

Superdom: Better and Simpler ES6 DOM Manipulation

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

Getting started

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

Select

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"'];

Generate

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 elements

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?

Attributes

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.

Get attributes

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:

  • html (alias of innerHTML): retrieve a list of the htmls
  • text (alias of textContent): retrieve a list of the htmls
  • parent (alias of parentNode): travel up one level
  • children: travel down one level

Set attributes

// 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>
`;

Remove an attribute

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;

Classes

It provides an easy way to manipulate the classes.

Get 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 a class

// Add the class 'test' (different ways)
dom.a.class.test = true;    // #class-make-true
dom.a.class = 'test';       // #class-push

Remove a class

// Remove the class 'test'
dom.a.class.test = false;    // #class-make-false

Manipulate

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';

Events

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;

Testing

We are using Jest as a Grunt task for testing. Install Jest and run in the terminal:

grunt watch

Download Details:

Author: franciscop
Source Code: https://github.com/franciscop/superdom 
License: MIT license

#javascript #es6 #dom 

Rupert  Beatty

Rupert Beatty

1684207573

How to Check If The File Exists in Bash

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.

File Test Operators

Many file test operators exist in Bash to check if a particular file exists or not. Some of them are mentioned in the following:

OperatorPurpose
-fIt is used to check if the file exists and if it is a regular file.
-dIt is used to check if the file exists as a directory.
-eIt is used to check the existence of the file only.
-h or -LIt is used to check if the file exists as a symbolic link.
-rIt is used to check if the file exists as a readable file.
-wIt is used to check if the file exists as a writable file.
-xIt is used to check if the file exists as an executable file.
-sIt is used to check if the file exists and if the file is nonzero.
-bIt is used to check if the file exists as a block special file.
-cIt is used to check if the file exists as a special character file.

Different Examples to Check Whether the File Exists or Not

Many ways of checking the existence of the regular file are shown in this part of the tutorial.

Example 1: Check the Existence of the File Using the -F Operator with Single Third Brackets ([])

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.

Example 2: Check the Existence of the File Using the -F Operator with Double Third Brackets ([[ ]])

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.

Example 3: Check the Existence of the File Using the -F Operator with the “Test” Command

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.

Example 4: Check the Existence of the File with the Path

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:

Conclusion

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/

#bash #file 

Как проверить, существует ли файл в Bash

Различные типы файлов используются в Bash для разных целей. В Bash доступно множество опций, позволяющих проверить, существует ли конкретный файл или нет. Существование файла можно проверить с помощью операторов проверки файлов с командой «test» или без команды «test». В этом руководстве показаны цели различных типов операторов проверки файлов для проверки существования файла.

Операторы проверки файлов

В Bash существует множество операторов проверки файлов, чтобы проверить, существует ли конкретный файл или нет. Некоторые из них упоминаются в следующем:

ОператорЦель
-fОн используется для проверки того, существует ли файл и является ли он обычным файлом.
Он используется для проверки существования файла в виде каталога.
Он используется только для проверки существования файла.
-ч или -лОн используется для проверки существования файла в виде символической ссылки.
Он используется для проверки того, существует ли файл как читаемый файл.
-wОн используется для проверки того, существует ли файл как файл, доступный для записи.
-ИксОн используется для проверки того, существует ли файл как исполняемый файл.
Он используется для проверки того, существует ли файл и не равен ли он нулю.
Он используется для проверки того, существует ли файл в виде специального блочного файла.
Он используется для проверки того, существует ли файл как файл со специальными символами.

Различные примеры проверки существования файла

В этой части руководства показано множество способов проверки существования обычного файла.

Пример 1. Проверка существования файла с помощью оператора -F с одиночными третьими скобками ([])

Создайте файл 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» выполняется, чтобы проверить, существует ли файл или нет.

Пример 2. Проверка существования файла с помощью оператора -F с двойными третьими скобками ([[ ]])

Создайте файл 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» выполняется, чтобы проверить, существует ли файл или нет.

Пример 3: Проверка существования файла с помощью оператора -F с командой «Тест»

Создайте файл 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

Сценарий выполняется дважды в следующем сценарии. При первом выполнении аргумент не передается. Существующее имя файла дается во втором исполнении.

Пример 4. Проверка существования файла с указанием пути

Создайте файл 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/

#bash #file 

如何在 Bash 中检查文件是否存在

Bash 中出于不同的目的使用不同类型的文件。Bash 中有许多选项可用于检查特定文件是否存在。可以使用带有“test”命令或不带有“test”命令的文件测试操作符来检查文件是否存在。本教程显示了不同类型的文件测试操作符检查文件是否存在的目的。

文件测试操作员

Bash 中存在许多文件测试运算符来检查特定文件是否存在。下面提到了其中一些:

操作员目的
-F它用于检查文件是否存在以及它是否是常规文件。
-d它用于检查文件是否作为目录存在。
-e它仅用于检查文件是否存在。
-h 或 -L它用于检查文件是否作为符号链接存在。
-r它用于检查文件是否作为可读文件存在。
-w它用于检查文件是否作为可写文件存在。
-X它用于检查文件是否作为可执行文件存在。
-s它用于检查文件是否存在以及文件是否为非零。
-b它用于检查文件是否作为块特殊文件存在。
-C它用于检查文件是否作为特殊字符文件存在。

检查文件是否存在的不同示例

本教程的这一部分显示了许多检查常规文件是否存在的方法。

示例 1:使用带有单个三分括号 ([]) 的 -F 运算符检查文件是否存在

使用以下脚本创建一个 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”命令来检查文件是否存在。

示例 2:使用带有双三分括号 ([[ ]]) 的 -F 运算符检查文件是否存在

使用以下脚本创建一个 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”命令来检查文件是否存在。

示例 3:使用带有“测试”命令的 -F 运算符检查文件是否存在

使用以下将文件名作为命令行参数的脚本创建 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

该脚本在以下脚本中执行了两次。第一次执行时不给出参数。第二次执行时给出一个现有的文件名。

示例 4:使用路径检查文件是否存在

使用以下脚本创建 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/

#bash #file 

Rupert  Beatty

Rupert Beatty

1684202959

How to Check The Number Of Arguments in The Bash Script

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.

Different Uses of Checking the Number of Arguments

The uses of checking the number of arguments are shown in this part of the tutorial using multiple examples.

Example 1: Count the Total Number of Arguments Using “$#”

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:

Example 2: Print the Argument Values Based on the Argument Length

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.

Example 3: Calculate the Average of the Argument Values

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.

Example 4: Print the Error Message Based on the Argument Values

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.

Conclusion

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/

#bash #script #number #arguments