add class name using JavaScript

If-Statement inside JavaScript Class Constructor

To add multiple classes, we have to separate their name with space such as «class1 class2» . We have to click the given HTML button «Get Class name» to see the effect.

If-Statement inside JavaScript Class Constructor

I am trying to use conditional logic inside a JavaScript Class constructor.

Context: I am creating a 2d grid in a double for loop, with each cell having a property of North, South, East, and West. To keep in bounds of the 2d Grid, I am trying to only create a cell that has N,S,E properties, if that cell lay on the edge with col equal to 0.

For a 4×4 grid, I try to build this item and I keep getting the error, «Uncaught SyntaxError: Unexpected token ‘!='». So I believe the issue is just with my poor knowledge of Javascript Syntax. Any Suggestions?

class Cell < constructor(row,col)< this.visited = false; this.row = row; this.col = col; this.edges = < if(row!=0)< north:1, >, if(row!=3))< south:1, >, if(col!=0))< west:1, >, if(col!=3))< east:1, >, > > > 

I would use with ternary operators instead of if statements there. About Conditional (ternary) operator please read as below:

The Conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as a shortcut for the if statement.

For example this one is a good syntax for your case:

const row = 2; const col = 3; const edges = < north: row != 0 ? 1 : 0, south: row != 3 ? 1 : 0, west: col != 0 ? 1 : 0, east: col != 3 ? 1 : 0 >;console.log(edges);

You can use the ternary operator

You cannot use if statements inside of an object literal. Instead, you should use the if statement to assign to the field of the object directly:

this.edges = <>; if (row != 0) < this.edges.north = 1; >// etc. 

This syntax wont work. Create an empty object and add property afterwards.

class Cell < constructor(row,col)< this.visited = false; this.row = row; this.col = col; this.edges = <>; if(row!=0) < this.edges.north = 1; >if(row!=3)) < this.edges.south = 1; >if(col!=0)) < this.edges.west = 1; >if(col!=3)) < this.edges.east = 1; >> > 

C# If Else, Example explained. In the example above, time (22) is greater than 10, so the first condition is False.The next condition, in the else if statement, is also False, so we move on to the else condition since condition1 and condition2 is both False — and print to the screen «Good evening». However, if the time was 14, our program …

How to add a class to an element using JavaScript?

The class attribute can be used in CSS to do some tasks for the elements with the corresponding class name. In this article, we are discussing how to add a class to an element using JavaScript. In JavaScript, there are some approaches to Add a class to an element. We can use the .className property or the .add() method to add a class name to the particular element.

Читайте также:  Double positive infinity java

Now, let’s discuss the approaches to add a class to an element.

Using .className property

The .className property sets the class name of an element. This property can be used to return the value of the class attribute of an element. We can use this property to add a class to an HTML element without replacing its existing class.

To add multiple classes, we have to separate their name with space such as «class1 class2» .

If a class is already declared for an element, and we need to add a new class name to the same element then it should be declared by inserting a space before writing the new class name otherwise, it will overwrite the existing class name. It can be written as follows:

  document.getElementById("div1").className = " newClass";

In the above code, we have inserted a space before newClass .

Syntax

The commonly used syntax of this property to set or to return the class name is given below.

To set the class name

To return the class name

The example of using the .className property is given as follows.

Example — Adding the class name

In this example, we are using the .className property for adding the «para» class to the paragraph element having id «p1» . We are applying the CSS to the corresponding paragraph using the class name «para» .

We have to click the given HTML button «Add Class» to see the effect.

    .para  

Hello World :)

Click the following button to see the effect.

function fun()

How to add a class to an element using JavaScript

After clicking the given button, the output will be —

How to add a class to an element using JavaScript

In the next example, we are getting the name of the class by using the .className property.

Example — Getting the class name

In this example, we are using the .className property to get the class names of the paragraph element having id = «p1» .

We have to click the given HTML button «Get Class name» to see the effect.

   

Hello World :)

Welcome to the javaTpoint.com

Click the following button to get the class name.

function fun()

How to add a class to an element using JavaScript

After clicking the given button, the output will be —

How to add a class to an element using JavaScript

Using add() method

Now, let’s see the second approach of adding the class name using JavaScript. We can use the add() method to add a class name to the particular element.

Syntax
element.classList.add("class name");
Example

In this example, we are using the add() method to add a class name to the paragraph element having id = «p1» . We have to click the given HTML button «Add Class» to see the effect.

    .para  

Hello World :)

Click the following button to see the effect.

function fun()

How to add a class to an element using JavaScript

After clicking the given button, the output will be —

How to add a class to an element using JavaScript

JavaScript if/else Statement, The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. The if/else statement is a part of JavaScript’s «Conditional» Statements, which are used to perform different actions based on different conditions. In JavaScript we have the following …

Tips for Writing better Conditionals in JavaScript

If you are working with JavaScript, you would be writing a lot of code with a lot of conditions involved. At first, conditionals may seem easy to learn, but there is more to it than to write a few if-else statements.

Читайте также:  Java часы со стрелкой

Object-oriented programming allows one to avoid conditions and replace them with polymorphism and inheritance. You should follow these principles as much as possible. But on the other side, you may end up with the conditionals in your code for various reasons. This article’s purpose is to help you organize the conditional statements.

Tips for writing code with conditionals:

    Array.includes: You can use array.includes() method for multiple conditions. The array.includes() method is used to determine if a particular element is present in the array. It returns “true” or “false” Example: The following code demonstrates, how to check if the animal is a “lion” or a “dog”.

Источник

If statement to find a class in javascript

Check it https://jsbin.com/lecuro/edit?html,js,output JS Solution 3: If you call and there are no DOM elements with that class name, it will return 0. will return an HTMLCollection, which is almost like an array, so you’ll just do: That will alter the inner HTML mark-up of every element with the specified class name, just change to the name of your class. Question: i am currently feeling my way through simple javascript tasks, i am trying to put together an if/else statement in javascript that check the h1 on my page to see if one of possibly three classes exist, after the javascript determines which class is attached to the h1 i need it to pushes out a specific text into the h1.

If statement to find a class in javascript

Using javascript how can I check which one of these have ui-state-active, because I need an if statement to check whether the ui-state-active is activated on status history and do something.

var statusHistory = document.getElementById('order-journey-summary-tab'); if(statusHistory.classList.contains('ui-state-active')) < // do stuff >
if($('#order-journey-summary-tab').hasClass('ui-state-active')) < // do stuff >

This can easily be checked with the new HTML5 classList API:

document.getElementById('customers-tab').classList.contains('ui-state-active'); // Will return true if element has class 

Otherwise, you’ll have to use the old way:

document.getElementById('customers-tab').className.indexOf('ui-state-active') != -1; // Will return true if element has class 

I would recommend using the hasClass() property in jQuery though!

You could use jQuery’s hasClass() .

Otherwise you need to check the className property of the element w/ plain ol’ JavaScript.

Condition to check whether any element has a specific class, You can use .querySelector(selector) to search for children of some element . !!element.querySelector(selector) will return true if it finds

Checking if an element has one class vs another alway returns true

I’m trying to check if an element has one of two classes. If it doesn’t then it should run some other function. I’m using the || or operator but, regardless of the if statement, it always returns true and runs the inner functionality, which is not what I expect. Is my syntax wrong here?

if (!elm.hasClass('report-error') || !elm.hasClass('data-error')) < // Do something >

Your condition will be true when the element does not have both classes, which includes the scenarios where the element has neither class or only one of the classes. It will only become false when the element has both classes.

You currently have the condition (!A OR !B), which his logically equivalent to !(A AND B).

It sounds like you want it to be true when the element has neither of the two classes. In that case, what you want is !(A OR B), which can also be written as (!A AND !B).

Читайте также:  Python delete file by path

Both of these statements will do what you want:

// !(A OR B) if (!(elm.hasClass('report-error') || elm.hasClass('data-error'))) < // Has neither class, so do something else >
// !A AND !B if (!elm.hasClass('report-error') && !elm.hasClass('data-error')) < // Has neither class, so do something else >

You could also keep it super simple (and more readable) by checking if it has one class or the other, and handling the «neither» case in the the ELSE statement:

if (elm.hasClass('report-error') || elm.hasClass('data-error')) < // Has one class or the other >else < // Has neither class, so do something else >

Sounds like a logical error — does not have X or does not have Y. This will be true in most cases.

if (!(elm.hasClass('report-error') || elm.hasClass('data-error'))) < // Do something >

That will check if any of the classes are there, then invert it (so not there).

If and else statement check if has class, .toggleClass() is for this specific purpose. From the doc. Add or remove one or more classes from each element in the set of matched

Javascript — if else statement that uses document.getElementsByClassName with three possible scenarios

i am currently feeling my way through simple javascript tasks, i am trying to put together an if/else statement in javascript that check the h1 on my page to see if one of possibly three classes exist , after the javascript determines which class is attached to the h1 i need it to pushes out a specific text into the h1.

the script i am tinkering with is document.getelementsbyclassname («pagetitle_contact»)[0].innerHTML = «sample text 1»;

i have three possible class names: pagetitle_home pagetitle_about pagetitle_contact

help is much appreciated, if more info is needed let me know 🙁

var elements = document.getElementsByClassName("first_class"); if (elements.length) < elements[0].innerHTML = "first text"; >else < elements = document.getElementsByClassName("second_class"); if (elements.length) < elements[0].innerHTML = "second text"; >else < elements = document.getElementsByClassName("third_class"); if (elements.length) < // can be left out if the presence of one of the three classes is guaranteed elements[0].innerHTML = "third text"; >> > 

Please notice that it will only modify one of those elements, since we’re using if/then/else. If you want to modify the first element of all these classes, you just need 3 if/then :

var elements = document.getElementsByClassName("first_class"); if (elements.length) < elements[0].innerHTML = "first text"; >elements = document.getElementsByClassName("second_class"); if (elements.length) < elements[0].innerHTML = "second text"; >elements = document.getElementsByClassName("third_class"); if (elements.length)

I made a fiddle for you . Check it

 if (document.getElementsByClassName("pagetitle_contact").length) < document.getElementsByClassName("pagetitle_contact")[0].innerHTML = "sample text 1"; >if (document.getElementsByClassName("pagetitle_home").length) < document.getElementsByClassName("pagetitle_home")[0].innerHTML = "sample text 2"; >if (document.getElementsByClassName("pagetitle_about").length)

If you call document.getElementsByClassName(«CLASS_NAME»).length and there are no DOM elements with that class name, it will return 0.

document.getElementsByClassName(«CLASS_NAME») will return an HTMLCollection, which is almost like an array, so you’ll just do:

var elements = document.getElementsByClassName("CLASS_NAME"); // Get every element with that class name for(var i = 0; i < elements.length; i++) // Iterate over every single element in the collection elements[i].innerHTML = "Text to be inserted"; // Alter the HTML inside the current element 

That will alter the inner HTML mark-up of every element with the specified class name, just change "CLASS_NAME" to the name of your class.

As a general recommendation, there should be exactly one h1 tag on your page. So why don't you query that single h1 tag, and then query which CSS class is attach to it?

Javascript - jQuery - If element has class do this, Well you said that you want to know if "any" element has a certain class but your selector in your if statement is only targetting the

Источник

Оцените статью