Select the final word and enclose it within a span class

I have a task where I need to identify the last word in a class and then enclose it with a span element so that I can style it using JavaScript.

<h1 class="title>A long tile</h1>
<h2 class="title>A long tile</h2>

should be transformed into

<h1 class="title>A long <span class="last-word">tile</span></h1>
<h2 class="title>A long <span class="last-word">tile</span></h2>

I found some jQuery solutions on Stack Overflow that were helpful, but I prefer a pure Javascript version.

I managed to make it work for the first element on the page with this code...

var paras = document.querySelector('.title');

function wrapLastWord(elem) {
  const textContent = elem.textContent.split(" ");
  const lastWord = textContent.pop();

  const updatedContent = textContent.join(" ") + (textContent.length > 0 ? ` <span class='last-word'>${lastWord}</span>` : lastWord);

  elem.innerHTML = updatedContent;
}

wrapLastWord(paras)

However, my goal is to target all elements with the .title class, so I attempted to use querySelectorAll and forEach, but it's not working as expected.

var paras = document.querySelectorAll('.title');
paras.forEach(function wrapLastWord(elem) {

      const textContent = elem.textContent.split(" ");
      const lastWord = textContent.pop();

      const updatedContent = textContent.join(" ") + (textContent.length > 0 ? ` <span class='last-word'>${lastWord}</span>` : lastWord);

      elem.innerHTML = updatedContent;
    }

    wrapLastWord(paras)
                  
})

I would appreciate any guidance or suggestions for making this work correctly or considering a different approach.

Answer №1

First and foremost, there is a syntax error in the second line missing an "

<h1 class="title>A long <span class="last-word">tile</span></h1>
<h2 class="title>A long <span class="last-word">tile</span></h2>

This should be corrected to:

<h1 class="title">A long <span class="last-word">tile</span></h1>
<h2 class="title">A long <span class="last-word">tile</span></h2>

When it comes to extracting values using JavaScript, you can easily do so by:

const spanText = document.querySelector('.last-word').innerText
console.log(spanText)

const lastWords = document.querySelectorAll('.last-word')
console.log(lastWords, "<-array like object")

lastWords.forEach((word) => {
  console.log(word.innerText)
})

Regarding your function:


var paras = document.querySelectorAll(".title");
console.log(paras);
paras.forEach(function wrapLastWord(elem) {

  const textContent = elem.innerText.split(" ");
  console.log(textContent, ' textContent')
  const lastWord = textContent.pop();
  console.log(lastWord, 'last word')

  const updatedContent = ` <span class='last-word'>${lastWord}</span>`;     
  console.log(updatedContent, 'updatedContent')
})

You have successfully created updatedContent, now you need to decide how you want to utilize it. Consider using one of the append methods mentioned in the documentation if you wish to add it to your webpage.

Answer №2

Big shoutout to @JimithyPicker for guiding me towards the solution!

Behold, behold, my ultimate code:

const headings = document.querySelectorAll(".heading");

headings.forEach(function appendLastWord(element) {
    const textContent = element.textContent.split(" ");
    const lastWord = textContent.pop();

    // Wrap the last word in a span tag if it's not the only word in the sentence
    const updatedContent = textContent.join(" ") + (textContent.length > 0 ? ` <span class='final-word'>${lastWord}</span>` : lastWord);

    element.innerHTML = updatedContent;
});

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

Encountered a 404 error (not found) while making a GET request with axios

I encountered an issue with my pizza shop application built with Next.js. Whenever I run the app on my computer, I come across this error: https://i.sstatic.net/tsQzZ.png The error disappears after refreshing the page. Here is my index.js file: import ax ...

Add an HTML template tag in Vuetify using scripting

This is my current template tag: <template> <h1>Explore in VR</h1> </template> Within my script tag, I've included the following code: var viewer = new AFrame.WebVRViewer(); viewer.setSize(window.innerWidth, window.innerHeig ...

Tips for Showing a Portion of an Object in React JS

Need help displaying subitems of an object. I can display the main item but struggling with subitems. Here's the attached image for reference: https://i.sstatic.net/WTgb3.png I'm having trouble displaying the comments section in the object. I&a ...

How come the useState function remains undefined, even when initialized with a default value?

I attempted to set an empty array as the default value for a state using the useState hook in React. However, when I try to check the type of testing with console.log(Array.isArray(testing)); or simply log testing, it always displays undefined regardless o ...

Having issues with accessing data from Informix database in PHP due to an undefined index?

I am encountering the following error multiple times per row: Notice: Undefined index: enviopre in /opt/lampp/htdocs/pruebax/pruebaxone.php on line 34 Notice: Undefined index: enviofra in /opt/lampp/htdocs/pruebax/pruebaxone.php on line 35 Notice: Undef ...

AngularJS - development of a service entity

After deliberating between posting in the Angular mailing list or seeking assistance from the JavaScript community, I have decided that this is more of a JavaScript question. Hopefully, the knowledgeable individuals on Stack Overflow can provide a quicker ...

The argument supplied to the `openUri()` function should be in the form of a string, but instead, it is displaying as "undefined". Please ensure that the initial parameter provided to either `mongoose.connect()`

Encountered error: The `uri` parameter passed to `openUri()` must be a string, but it is currently set as "undefined". Please ensure that the first parameter in either `mongoose.connect()` or `mongoose.createConnection()` is a valid string. Below are the ...

What could be causing the Uncaught ReferenceError message that says scrollToM is not defined in my code?

Can someone help me with this code for creating a single page website? $(window).load(function() { function filterPath(string) { return string .replace(/^\//,'') .replace(/(index|default).[a-zA-Z]{3,4}$/,'') ...

Creating a Class in REACT

Hello fellow coding enthusiasts, I am facing a minor issue. I am relatively new to REACT and Typescript, which is why I need some assistance with the following code implementation. I require the code to be transformed into a class for reusability purposes ...

What is preventing me from integrating angular-cookies into my application?

I'm struggling to resolve this issue where I can't seem to make it work. My aim is to integrate NgCookies (angular-cookies) into my application, but all I'm encountering are errors. This is what I currently have: JS files being included: ...

Exploring the depths of Vue.js routing through nesting

My Current Route is function route(path, view) { return { path: path, meta: meta[path], component: resolve => import(`pages/${view}View.vue`).then(resolve) } } route('/', 'Home'), route('/help', 'Help ...

Error encountered when using prisma findUnique with where clause

Trying to set up a Singup API using ExpressJS and Prisma is proving to be a bit challenging. The issue arises when I attempt to verify if a given email already exists in my database. Upon passing the email and password, an error is thrown stating Unknown ...

I'm struggling to adjust the height of a div based on whether a list item within it contains a nested unordered

I have been working on a horizontal menu that is functioning well for me. However, according to the design requirements, I need to adjust the height of <div id="nav-subMenu"></div> if the main/parent menu li does not have any submenus or ul. Th ...

What is the best way to include a disable option or default option in a select box?

I am incorporating react material in react using the select component. My goal is to include a first disabled option that says "please select item." This is how it's currently implemented in HTML: <select name="tagging"> <option sel ...

unnecessary files in the node_modules directory in Rails

I am a beginner in Node.js and unfamiliar with npm and modular JavaScript. After using the browserify-rails gem, I noticed that there are multiple files from a GitHub repo stored in the node_modules folder after running npm install. Since I only require ...

Oops! Looks like there's an issue with reading the property 'value' of undefined in React-typeahead

Having some issues with setting the state for user selection in a dropdown menu using the react-bootstrap-typeahead component. Any guidance or resources on this topic would be highly appreciated. Details can be found here. The function handleAddTask is su ...

Does the AngularJS Controller disappear when the DOM element is "deleted"?

One challenge I encountered is regarding a directive that is connected to an angularjs controller, as shown below: <my-directive id="my-unique-directive" ng-controller="MyController"></my-directive> In the controller, at a certain point, I ne ...

Determine the hue of a specific location on a geometric surface

I'm currently working with THREE.js for my scene rendering and I have a complex question - how can I retrieve the color of a specific point on a geometry face? When I mention color, it's not just the face or material color that I'm interest ...

Modify the contents of an array within a string using JavaScript

let message = "hello https://ggogle.com parul https://yahoo.com and http://web.com"; let url = ["https://ggogle.com", "https://yahoo.com", "http://web.com"]; I'm trying to replace all URLs in the 'message' array with "***" from the 'ur ...

"An issue has arisen in MongoDB when attempting to save data, resulting in an error message

Having trouble inserting data into MongoDB with Node.js. Encountering an error in the final line of code. Here are the execution logs: { _id: 56e90c1292e69900190954f5, nfs: [ 'ebdp1', 'ebdp2', 'ebdp3', 'ebdp4' ], s ...