What is the process to convert the output HTML tag <b></b> to <strong></strong>?

Looking for help on how to replace the <b></b> tags with <strong></strong> tags within a specific div element:

For example:

<div id="aaa">hello<b>wow</b>!</div>

Need to achieve this using JavaScript:

<div id="aaa">hello<strong>wow</strong>!</div>

If anyone can offer assistance, it would be greatly appreciated. Thanks in advance.

***** My main goal is to change the output HTML code from <b></b> to <strong></strong> for W3C validation. Is there a way to accomplish this? **

Alternatively, is there a solution that involves ASP.NET and C# to achieve this conversion?

Answer №1

Check out the code snippet below:

var main, elements;

main = document.getElementById( 'test' );
elements = main.getElementsByTagName( 'b' );

toArray( elements ).forEach( function ( element ) {
    var newElement = document.createElement( 'strong' );
    newElement.textContent = element.textContent;
    element.parentNode.replaceChild( newElement, element );    
});

where toArray refers to your chosen array-like to array conversion function. I recommend using this one:

function toArray( arrayLike ) { return [].slice.call( arrayLike ); }

See it in action: http://jsfiddle.net/mJSyH/3/

Important: This code may not be compatible with IE8.

Answer №2

If you want to select all the <b> elements within a specific element, you can gather them and transfer all child nodes to a new <strong> element. After that, simply replace the <b> tags with the <strong> tags.

<div id="aaa">hello<b>wow</b><b>2</b><b>3</b>!</div>

<script>
  var container = document.getElementById("aaa")
  var find = container.getElementsByTagName("b");
  var bold, strong;

  while (bold = find[0]) {
    strong = document.createElement("strong");

    while (bold.firstChild) {
      strong.appendChild(bold.firstChild);
    }

    bold.parentNode.replaceChild(strong, bold);
  }
</script>

The reason you can assign bold = find[0] repeatedly is because as the <b> elements are removed from the HTML document, they are also simultaneously eliminated from the NodeList find.

To view the most recent version, visit http://jsbin.com/eqikaj/13/edit.

Answer №3

By utilizing jQuery, you have the ability to locate every b element within the confines of your parent div container and then substitute each of them with strong, while duplicating the inner text of the original tag:

$('#xyz b').each(function() {
  $(this).replaceWith($('<strong>' + this.html() + '</strong>');
});

Answer №4

If you're a fan of jQuery, here's a simple way to achieve the same result:

$('b').replaceWith(function() {
        return $('<strong>').html($(this).html());
});

All you need to do is get your hands on the jQuery library, either by downloading it or including it somehow. Check out this link for more info: http://docs.jquery.com/Downloading_jQuery

Answer №5

One way to address this is by utilizing regular expressions:

var element = document.getElementById("aaa");
element.innerHTML = element.innerHTML.replace(/<b[^>]*>(.*?)<\/b>/ig, '<strong>$1</strong>');

While this method may not necessarily be faster than the alternatives mentioned earlier, the difference in performance is minimal (and often irrelevant in practical scenarios). Feel free to use whichever approach you deem most suitable.

Important: Instead of using a function like toArray, you can achieve the same outcome with the following code:

Array.forEach(elements, function() {  ... })

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

Infinite scrolling dropdown feature in the <Select> widget

I currently have around 20 typical HTML select widgets on my page. Each of these selects contains a large number of elements, for example: <select> <option>1</option> ... <option>3000</option> </select> As ...

Unable to display HTML content on a page using the foreach callback in JavaScript

I have a function that iterates through each element of an array and generates HTML content on the page while updating some properties using elements from the array. I am utilizing forEach to iterate over the elements of the array and innerHTML to display ...

Visualizing Data with Flot.js - A Comprehensive Guide

Does anyone know how to organize values in a flot histogram by day, merging them into one bar per day? I've been searching for a solution but can't seem to find one. __ If you have any ideas, please share! ...

Is the search feature in the Bootstrap 4 dual listbox plugin experiencing issues?

Using the filter option in Bootstrap 4 dual listbox, I noticed that when two results appear and I select the second option, the first option is automatically added to the list. https://www.jqueryscript.net/demo/Responsive-jQuery-Dual-Select-Boxes-For-Boot ...

A type guard for generics in TypeScript

I'm dealing with a variable that can be either of type C1[] or C2<C1>[]. How can I create a type guard for this variable? interface C<T>{ key: string; secret: T; } private isC(d: Foo[] | C<Foo>): d is C<Foo>[] { ret ...

Accessing Jquery's $.get function is currently not possible

I am experiencing difficulty fetching the contents of a json.txt file located in the same directory as this markup. Additionally, there are no errors appearing in Firebug. <!DOCTYPE html> <html> <head> <script type="text/ja ...

Express app throws an error when testing with Jest due to Multer being undefined

I am currently using jest to run tests on my TypeScript Express application that utilizes multer for file uploads. However, I encounter an error specifically during testing which says "TypeError: Cannot read properties of undefined (reading 'disk ...

Guide on inserting a canvas image among the various jsPdf components

After converting the specific <div> tag to <canvas> using html2canvas, I am looking to integrate this converted canvas image with other elements in JsPdf such as Autotables and texts. Appreciate any guidance or suggestions. Thank you. ...

Affixing a navigation bar to the top while scrolling

Does anyone know how to create a navigation bar that will "dock" to the top of the browser when scrolled to, and undock when scrolled back up? Check out my code snippet here: http://jsfiddle.net/gLQtx/ $(function() { var initPos = $('#stickyNav&apo ...

Ways to prevent mouse selection in an input field without disabling or making it read-only

Imagine this scenario: <input type="text"> The task at hand is to prevent text selection within the <input> field. ...

Node.js Express Timer with API for Initializing/Stopping/Reinitializing

I have a functional (though not the most aesthetically pleasing) solution for this problem. My expertise lies mainly in C# and Powershell, so I am relatively new to Node.js & Express. What I am aiming for is a simple webpage at localhost:8080/sw that featu ...

Ways to activate a javascript function upon the visibility of a button changing

Utilizing a third-party JS and HTML library that I prefer not to update. The HTML contains an "apply all" button, and my goal is to have this button clicked when it is visible. <div class="confirm" ng-show="newFilters.length"> .... <butto ...

What is the connection between the forms authentication provider and the membership provider in ASP.NET MVC?

Could someone please explain the distinction between these two providers? Is it necessary to incorporate both of them for custom authentication purposes? Thank you. ...

Encountered an issue with instafeed.js due to CORS policy restrictions

Trying to implement an API that provides JSON data for use in a function. Required Imports: Importing Jquery, instafeed.min.js, and the API (instant-tokens.com). <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js& ...

Transforming jQuery into Angular - Press Button to update choices in Dropdown List

I am looking to integrate some AngularJS features into a website that currently utilizes jQuery. Here is the issue I am facing: With jQuery, clicking a button triggers a dropdown item change. Please refer to the jsfiddle below for an example: $('# ...

How to designate a try / catch block as asynchronous in TypeScript / JavaScript?

I am facing an issue where the code is not entering the catch block in case of an error, try { this.doSomething(); } catch (error) { console.error(error); } This problem occurs when "doSomething" returns a promise or runs asynchronous code. doSome ...

What is causing the issue with Next.js Json.map function not functioning correctly?

I am looking to develop a basic component that sources its data from a JSON list. While I am able to see the output of console.log(dat.CardId) on the website, it only works for console.log(). I cannot view the cards rendered by the .map function. The sty ...

Restrict certain sections of the website to authorized users only

In my game project, players are presented with two options: to play the game itself or to view global and local highscores. I have implemented a signup and login system where upon successful login, users can choose among playing the game, checking highscor ...

Creative Solution for Nested Forms

I am currently facing a challenge with nested forms in my PHP project. I need to include a form for AJAX image upload within another form so that I can pass the file path to the main form. The example code snippet is provided below; <form> <f ...

Issue encountered with an Asp.net website while being hosted on the server

After uploading my ASP.NET project to the server, I encountered the following error: Parser Error Description: An issue arose during the parsing of a resource necessary to handle this request. Please review the specific parse error details below and ma ...