JavaScript: Selecting parent elements using getElementsByClassName

I am dealing with the following HTML code:

<div class="item">
    <img class="item-image" src="${item.getImage()}"/>
    <p>${item.getName()}</p>
</div>

and JavaScript:

var classname = document.getElementsByClassName("item");

for (var i = 0; i < classname.length; i++) {
    classname[i].addEventListener('click', (e) => {
        addBorder(e.target);

    });
};

function addBorder(item) {
    if (item.tagName = 'DIV') {
        item.style.border = "3px solid red";
    }
}

Whenever I click on an item, a red border is added. However, if my click lands on the image or the paragraph within the item, the red border is drawn around them as well. I attempted to prevent this by adding an if statement in the addBorder function, but unfortunately it did not work. Is there a way to ensure that only the parent div gets the red border, even if the click falls inside the p or img elements?

Answer №1

When we say item.tagName = 'DIV', it actually means we are assigning the value of DIV to item.tagName. To compare, all you have to do is replace item.tagName = 'DIV' with item.tagName === 'DIV'.

if (item.tagName === 'DIV') {
    item.style.border = "3px solid red";
}

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

struggling with beginner-level JavaScript issues

Hey there, I've been running into a bit of an issue with my basic javascript skills: function tank(){ this.width = 50; this.length = 70; } function Person(job) { this.job = job; this.married = true; } var tank1 = tank(); console.log( ...

Could you share the most effective method for implementing a live search feature using javascript or jquery?

While attempting to create a live search for a dataset containing over 10,000 rows, I specified the DOM structure that is available. Despite my efforts to check each result after a single input during the live search process, my browser keeps hanging. Is t ...

The functionality of the Ajax script seems to be optimized for Firefox browsers exclusively, as it is encountering issues with compatibility on other

My code works perfectly in Firefox, but I'm encountering an issue in all other browsers. Specifically, I'm getting the error message "SyntaxError: JSON Parse error: Unexpected EOF" on line if (this.readyState == 4 && this.status == 200). ...

Error message "TypeError: onClick is not a function" occurs when attempting to use a prop in a functional component

I am encountering issues while trying to utilize the onclick function as props. It shows an error message 'TypeError: onClick is not a function' when I click. What should I do? 7 | <Card 8 | onClick={() => onClick(dish ...

Using Backbone for the front end and Node.js for the backend, this website combines powerful technologies

Currently, I am in the process of developing a new website that will function as a single-page application featuring dialog/modal windows. My intention is to utilize Backbone for the frontend and establish communication with the backend through ajax/webs ...

Platform error: Responses not specified for DIALOGFLOW_CONSOLE

I've been struggling with this issue for almost a day now and I'm at a loss for what else to try. For some reason, Dialogflow Fulfillment in Dialogflow ES is refusing to make any HTTP calls. Every time I attempt, I receive the same error message ...

Fluctuate the window.location with jQuery or javascript

My goal is to create a functionality where clicking an image will toggle the window.location url between '#' and '#footer'. The current code I have for this is: <script> function clickarrow(){ var rd=Math.floor(Math.random() ...

AInspector WCAG evaluation found that mat-select does not meet level A compliance standards

As I work on making my website WCAG level A compliant, I've encountered an issue with the mat-select component in Angular material. After running checks with the AInspector extension for Firefox, it appears that the mat-select component lacks aria-con ...

Tips on providing validation for either " _ " or " . " (select one) in an Angular application

I need to verify the username based on the following criteria: Only accept alphanumeric characters Allow either "_" or "." (but not both) This is the code snippet I am currently using: <input type="text" class="form-control" [ ...

Is there a way to detect duplicate usernames in a form without actually submitting the form, and then automatically focus on the username field if a duplicate is

I need help with a user registration form that I am creating. I want the form to automatically search for an existing username as soon as the user starts typing in the username field. If the username already exists, I want the field to receive focus. In my ...

jQuery Masonry now renders "row blocks" as opposed to trying to fit elements into place

Have you ever heard of the jQuery masonry plugin? It's a great tool for placing images in "blocks" instead of trying to squeeze them into empty spaces. Take a look at this explanation: But how can we minimize those pesky "voids"? HTML: <!-- This ...

What are the steps for setting up API REST calls proxy for a frontend hosted on Netlify?

While testing locally, I am able to successfully post a call and access it through Netlify. However, once I host the frontend app on Netlify, the POST Proxy is being set to the Netlify URL. The hosted URL: Upon clicking "Sign Up" and then clicking on "Si ...

What is the best way to locate the key with the greatest value in an array that is less than or equal to a certain

In my data structure, I have an array that maps user levels to the minimum points required for each level. Here's how it looks: $userLevels = array(0 => 0, 1 => 400, 2 => 800); The keys represent user levels and the values represent the min ...

Angular.js dynamically changing ng-class based on long-polling updates to a monitored variable

Currently utilizing angular.js for my project. I am implementing long polling with a server and would like to dynamically update an element in the view, specifically one with a class of 'updated', whenever the value of build_tag is incremented. ...

Transfer or duplicate an SVG image from the bottom div to the top div

Is there a way to move a div from the chart_div to the movehere div? I've tried duplicating it below the current svg, but I'm having trouble targeting just the header row ('g' element) specifically. Here is the HTML: <script type= ...

Algorithm for encryption and decryption using symmetric keys

Can anyone recommend a reliable symmetric-key encryption algorithm that works seamlessly with both JavaScript and Java programming languages? I attempted to implement one myself, but encountered some complications related to encoding. ...

Uploading pictures to a directory and storing their filenames in a database with the help of PHP

I'm facing a challenge trying to upload 2 files into a folder and save their names and image paths in a database. Below is my HTML code for reference: <input class="field2" type="file" name="file[]" multiple="multiple" /> Here is the PHP code ...

Issue: Undefined onClick function for HTML when using Node.js, NPM, and Parcel

I am currently working on a weather application using Node.js, NPM, and Parcel for development. To ensure OpenLayers functions properly, I need to incorporate these technologies, even though I'm not very familiar with them. One key aspect of my proje ...

The download attribute is not functioning properly on both Chrome and Edge browsers

I've been trying to use the download attribute, but it doesn't seem to be working. I have also attempted to use the target attribute to see if there are any issues with downloading from the server or from a web (https) source. Unfortunately, noth ...

Make sure two elements are siblings in JavaScript / jQuery

Looking at the HTML structure below: <div class="wrap"> <div id="a"></div> <div id="b"></div> </div> A statement is presented as false: ($('#a').parent() == $('#b').parent()); //=> false ...