Strategies for pinpointing specific Elements within the Document Object Model

<html>
</head>
<body>
<div class="class1">
<p>text to update1</p>
<p>text to update2</p>
<p> </p>
</div>

<div class="class2">
<p>text to update1</p>
<p>text to update2</p>
<p> </p>
</div>

<button onclick="obj1.changeContent()">changeContent</button>

<script type="text/javascript">
var change= function()
{
}
change.prototype.changeContent=function()
{
// target specific element positions
var paragraph=document.getElementsByClassName("class1");
paragraph[0].innerHTML="hello";
paragraph[1].innerHTML="world";
var addthem = paragraph[2].innerHTML = second;

}

var obj1= new change;

</script>

</body>

When attempting the above process, I encountered an issue:

Uncaught TypeError: Cannot set property 'innerHTML' of undefined

This error occurs when trying to modify the innerHTML property of the second paragraph [1] element in the first class (Class1). How should I progress from here?

Answer №1

When reviewing your code, one key point to note is that after selecting the `.class1' elements you forgot to include [0].children. It's also important to remember that this will return a NodeList of matched elements rather than individual elements.

If you are familiar with jQuery, it might seem like chaining DOM methods to the NodeList is possible in native JavaScript, but unfortunately, it is not.

var change = function(){}

change.prototype.changehtml = function(){
  // targeting specific elements positions

  // okay selector 
  // var paragraphs = document.getElementsByClassName("class1")[0].children;
  // okayer selector
  // var paragraphs = document.getElementsByClassName('class1')[0].getElementsByTagName('p')

  // better more explicit selector  
  var paragraphs = document.querySelectorAll('.class1 > p');
  console.log( paragraphs )
  
  paragraphs[0].innerHTML="hello";
  paragraphs[1].innerHTML="hello1";
  
  // second is not defined
  var addthem = (paragraphs[2].innerHTML = second);

}

var obj1= new change;
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
<div class="class1">
<p>text to change1</p>
<p>text to change2</p>
<p> </p>
</div>

<div class="class2">
<p>text to change1</p>
<p>text to change2</p>
<p> </p>
</div>

<button onclick="obj1.changehtml()">changehtml</button>

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

Impact of shaking the browser window using JavaScript

Is there a way to create a browser screen shaking effect using javascript? I attempted to use window.moveBy(x,y) after researching online, but it didn't work as expected. Are there any libraries or code snippets available that can assist in achievin ...

What steps should I follow to utilize my spotify api token effectively?

Currently, I am working on developing a random playlist generator using the Spotify API. However, when I retrieve information from their server, I receive a 401 error code. I have managed to obtain an access token by following a tutorial. My main concern ...

Utilize mouseover to rotate the camera in three.js

Is it possible to utilize Three.js to rotate a camera and view an object from all angles upon hovering with the mouse? ...

Retrieve the duplicated items from an array by comparing two specific properties in JavaScript

I need assistance in identifying and retrieving duplicate objects within an array that share similarities in 2 specific properties. Consider the object structure below: let arry = [ {Level: "A-1", Status: "approved"}, {Level: &q ...

Creating a hierarchical JSON format for a nested commenting system

I have a JSON data representing a multi-level comment system as shown below: [{ "thread_id": 2710, "parent_id": "", "username": "string", "comment": "string", "postdate": "2017-06-09T07:12:32.000Z", "id": 1 }, { "thread_id": 2710, "parent_ ...

A function similar to setCell for modifying form fields in JqGrid

After searching through numerous answers from @Oleg, I couldn't find the solution I was looking for. I am dealing with a grid where I can edit inline in certain fields. Specifically, I am working with autocomplete functionality and when I select an it ...

Is there a way to interact with a DOM element through clicking and then pass it as a variable using PHP?

Is there a way to configure a table so that data from a specific row is sent to a PHP script and displayed in a section on the website when the user clicks on that row? I am looking to pre-fill a data entry form with information from a selected row, allow ...

Refresh the page to change the section using vue.js

I am currently working on a website using Laravel and Vue.js. I require two separate sections for the site: Site: https://www.example.com Admin: https://www.example.com/admin Within the resource/js/app.js file, I have included the main components as fo ...

Issue with Google Scripts Trigger not activating

I'm having difficulty getting my script to automatically run at around 6AM. I've set up the trigger for this script to run on a "Time-Driven" basis using the "day timer" option between 6-7 am. Despite setting up failure notifications to email me ...

How to center a div vertically in a window

I have a CSS layout that positions a div both horizontally and vertically relative to the window. It works well, but when I scroll down the page, the div stays centered as if the page hadn't moved. width:600px; height:300px; position:absolute; left:5 ...

modify the tr element within a jQuery context

I am attempting to convert a "yes" to a select dropdown that allows users to choose between yes and no. The HTML structure is as follows: <tr> <td>text</td> <td>no (needs to be changed via JS)</td> <td><a href="#"&g ...

The issue of the keyboard disappearing on Chrome for Android while switching between different input

Issue with Input Switching on Chrome for Android I am facing difficulty when trying to switch between two input fields. The HTML code is as follows: <input type="text"/> <input type="text"/> When I enter text in the first input and click on ...

click events in backbone not triggering as expected

It's puzzling to me why this is happening. The situation seems very out of the ordinary. Typically, when I want an action to be triggered on a button click, I would use the following code snippet: events:{ 'click #button_name':'somefun ...

I can't seem to figure out why document.getElementById().innerHTML isn't functioning properly

In my scenario, there exists a span with an identical value. echo "<span id='msgNotif1' class='badge' style='position:relative;right:5px;bottom:10px;'>".$number."</span>"; The $number variable holds a specific v ...

Encountering an error when integrating my library with MUI

Currently, I am working on developing a library that wraps MUI. One of the components I created is a Button, and here is the code snippet for it: import React, { ReactNode } from 'react' import Button from '@mui/material/Button'; impor ...

What steps are involved in transitioning from one mesh to another?

I am working with mesh1 and Mesh2, both of which have extrusion properties. mesh1 ->100 vertices mesh2 ->200 vertices In my programming code, I perform the following operations: mesh1.geometry.verticesNeedUpdate = true; mesh1 = Mesh2; mesh1.geomet ...

Setting up a recurring task with a while loop in a cron job

Discover numerous libraries dedicated to implementing cron jobs in NodeJS and Javascript, allowing for hosting on a server. Ultimately, cron jobs are simply repetitive tasks set to run at specific times/dates. This led me to ponder the distinction betwee ...

What is the method to access a form using jQuery? How can I extract the percentage symbol "%" from the entered amount?

I am working on developing a fee calculator using jQuery. In order to achieve this, I need to access forms. Here is the code I have so far: <form id="fee"> <input type="text" title="fee" placeholder="Place the amount that you would like to se ...

The initial step in the process is executing Redux

My app's global state is managed using redux. I have a global state called "shop" and its value is modified through the function "onFilterShops". const mapStateToProps = ({ shops }) => { return { shops: shops.shops } } const mapDi ...

jquery is showing up in the browserify bundle.js file, however, it is not functioning properly

Currently, I am trying to follow a brief tutorial on how to use Browserify. Despite following the instructions precisely, jQuery seems to not be working properly when bundled. Specifically, the button element in my app.js code is not appended to the body. ...