JavaScript: Activate the element with the first class of its children

This code is a visual representation of what I'm trying to accomplish...

<style>
.red{background:red}
.blue{background:blue}
</style>

<div id=test>
    <button>1</button>
    <button>2</button>
</div>

<script>
var firstBtn=document.getElementById("test").firstChild.className;

(firstBtn!="red")?firstBtn="red":firstBtn="blue";
</script>

If you want to see it in action, check out the jsFiddle link: http://jsfiddle.net/hnfeje2q/

While this code may be simple, as a newcomer to JavaScript, I may need some guidance...

Thank you!

Answer №1

To start, locate the div wrapper with the id of 'test' and then select the first child element within that wrapper using the following code. After that, you can assign the class 'red' to that specific element or button.

var wrapper = document.getElementById("test");
var firstButton = wrapper.childNodes[1];

// if the button doesn't have a red class, add it
if(firstButton.className.indexOf('red') == -1) {
    firstButton.className += ' red';
}

Alternatively, you can use the query selector method like this:

var firstButton = document.querySelector('#test button:first-child');
if(firstButton && firstButton.className.indexOf('red') == -1) {
    firstButton.className += ' red';
}

Answer №2

Instead of referring to the first button element with document.getElementById("test").firstChild, you will actually be referencing a text node that represents the space between the opening <div id="test"> tag and the first button.

For a more accurate reference to the first button element, use

document.querySelector('#test button:first-child')

var firstBtn = document.querySelector('#test button:first-child');
firstBtn.className = (firstBtn.className !== "red")? "red" : "blue";

Answer №3

Check out the latest version of this code on jsfiddle

var firstButton = document.querySelector('#test button:first-child');

if (firstButton !== "red") {
    firstButton.className = "red";
} else {
    firstButton.className = "blue";
}

Answer №4

To achieve this task, it is advisable to utilize the childNodes property instead of firstChild. The variable firstBtn should contain the class name in string format. In order to change it dynamically, modify the className attribute of the button using a similar syntax.

var firstBtn=document.getElementById("test").childNodes[1].className;
(firstBtn!="red")?document.getElementById("test").childNodes[1].className="red":document.getElementById("test").childNodes[1].className="blue";

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you use jQuery to select and manipulate multiple form inputs with a common class?

I am currently working on a program that requires at least one of various form inputs to have data in order for the user to submit the form. I was able to successfully code for a scenario with only one input field, but I am facing a challenge when it comes ...

Customizing textfield error color in MUI5 React based on conditions

I am looking for a way to dynamically change the color of error messages in my application, with warnings displaying in orange and errors in red. I prefer not to use useStyle as it is now deprecated in mui5. Below is the code snippet I have created: import ...

Problem encountered in Python with Selenium/WebDriver: Unable to convert script into a string

I am still a beginner with selenium and I'm trying to figure out how to run a javascript function using python and then utilize the value that it returns. I've encountered an error that has me stuck. Any assistance would be greatly appreciated. H ...

Trouble with JavaScript loading in HTML webpage

<!DOCTYPE html> <html> <head> <title>Breakout Game</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <canvas width="900" height="450" class="canvas"></canvas> ...

Ensure to verify the values of two variables when using a switch case statement

I'm working with two variables that can return true or false. My goal is to display a corresponding text message for each variable if it returns false. How can I effectively handle the ValidCheked and repeatChecked variables in a switch statement? ...

Automatically refresh a table within a webpage with updated database information without the need to manually refresh the

I'm a beginner in PHP and AJAX. The issue I am currently encountering is displaying a table on a JSP page and wanting to auto-update the table without refreshing the page every 10 seconds. I retrieve values from a database using a PHP page Below is t ...

Rotating out of the element with the transform rotate effect

I have rotated the text by 270 degrees and now I am facing the challenge of aligning it within another div. Here is the original image before I rotated the text: Below is the code I used for the layout: #infoside { background-color: #00ff00; flo ...

Adjusting the view to focus solely on the visible portion of the webpage

Is there a way to achieve zooming in and out on a website similar to how it works on the site ? I want only the visible area to zoom in or out when users interact with their browser. I searched online for a solution but couldn't find one. Any suggesti ...

Attempting to invoke a static function from a imported ES6 module

Currently, I am utilizing Firefox 56 with the setting dom.moduleScripts.enabled enabled. This configuration allows me to engage with native ES6 modules seamlessly. In my Vue2 component, there is a method that I have defined: import StorageZonesAjaxMethod ...

Alter the URL for Jquery AJAX post by utilizing radio buttons

I have a product search box that allows users to search by Cartridge Name or Printer Name. These are different SQL queries, so I have created separate PHP files for each query. However, I am facing challenges in using jQuery to check the value of the radio ...

Adjust picture dimensions when the window changes (using jQuery)

Hey there, I'm in need of some help resizing images on my webpage. I want the images to adjust their size when the page loads or when the browser is resized. The images can be either portrait or landscape, and they will be contained within a div that ...

Tips for positioning two divs in the center of a webpage, both horizontally and vertically, while also including a header and

Currently, I am in the process of creating a new web page with Bootstrap 4. This page consists of four main elements - a header, a footer, and two content boxes contained within divs. While I have successfully utilized default bootstrap classes to ensure t ...

Regular expression to match a string with a minimum of 10 characters, including at least 3 digits and alphanumeric

I need assistance creating a regular expression that validates strings with a minimum of 10 alphanumeric characters and at least 3 digits. For example: X6JV2YUW8T => True JN1H86LEKA => True 111JEJE134 => True A111111111 => True ABCDEFGHIJ =&g ...

Using file types in Vue 3: a beginner's guide

In order to use file-type to determine not only the extension but also ensure the headers are correct I would need to use one of the methods listed on their GitHub page. In version 19.0.0 it says fileFromFileType doesn't have such an export and in 16. ...

Node.js JSDOM unable to locate the 'parsingMode' property in the code

Is there a way to interact with the DOM of a JavaScript file using Node.js? var fs = require('fs'); var jsdom = require('jsdom'); var doc = jsdom.jsdom(fs.readFileSync("a.html"), null, { features: { FetchExt ...

I must create a dropdown and lift up feature similar to the one provided in the example

I am looking to implement a drop-down navigation bar on the top right and a pop-up button/links on the top left. The drop-down menu should appear when the screen size reaches a certain pixel width. If you can't see the drop-down navigation (NAV), adju ...

Having trouble getting the Keycloak provider to work with Next-Auth?

It's puzzling to me why my next-auth integration with Keycloak server is failing while the integration with Github is successful. import NextAuth from "next-auth" import KeycloakProvider from "next-auth/providers/keycloak"; import ...

Manipulating arrays in JavaScript through HTML processing

I'm encountering an issue while trying to send an array to a JavaScript function. Here's what I have so far: Within the controller: @data = [{date: '2014-08-17'}, {date: '2014-08-20'}].to_json In the view: <%= content_t ...

Utilizing ReactJS to make an Ajax request

I am trying to transfer data to individuals and then display it using the array map function. export default class App extends Component { constructor(props) { super(props); this.state = { persons: [], }; } componentDidMount() { $ ...

Execute various settimeout or display functions on various elements of a webpage

Just a heads up, I'm not really experienced in development. More on the newbie side of things, but eager to learn. I've been looking for an answer to my question, but so far haven't come across anything that fits my specific situation. It m ...