Exploring the Contrasts Between HTML String and Emphasizing the Variances

Challenge Description: The task is to compare two HTML input strings with various styling elements like strong, li, ol, line-through, etc. The goal is to display the original text and the edited text in two separate boxes on the screen. Any words missing in the edited text compared to the original text should be highlighted in red, while any additional words in the edited text should be highlighted in yellow.

https://i.sstatic.net/SKBT0.jpg

Expected Outcome: The first box should highlight deleted text in red, and the second box should highlight edited text in yellow.

https://i.sstatic.net/F86EH.jpg

Approached Solutions: 1. Experimented with the Diff Match Patch library, but encountered issues due to the presence of HTML tags in the input strings. Stripping the tags would result in loss of styling. 2. Attempted to use the HtmlDiff library, but it provided deleted and modified words in a single string, making it challenging to customize. Any guidance or assistance on this matter would be greatly appreciated. Thank you.

Answer №1

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<style>
html, body {
  font: normal 14px/1.4 sans-serif;
  background: #f1f1f1;
}

p {
  margin: 0 0 1rem;
}

ins {
  background: lightgreen;
  text-decoration: none;
}

del {
  background: pink;
}

table {
  border-collapse: collapse;
  width: 100%;
}
table td{
  border: 1px solid #ccc;
}

.card {
  background: #fff;
  border: 1px solid #ccc;
  border-radius: 3px;
  margin: 1rem;
  padding: 1rem;
}

.card .card {
  margin: 0;
  flex: 1 0 0;
}

.row {
  display: flex;
  justify-content: space-between;
  margin-right: -8px;
}

.col {
  display: flex;
  flex: 1 0 0;
  flex-direction: column;
  margin-right: 8px;
}
</style>
</head>
<body>
<div class="card">
  <div class="row">
    <div class="col">
      <h4>Old Version</h4>
      <div class="card" id="outputOriginal"></div>
    </div>
    <div class="col">
      <h4>Changes</h4>
      <div class="card" id="output"></div>
    </div>
    <div class="col">
      <h4>New Version</h4>
      <div class="card" id="outputNew"></div>
    </div>
  </div>
</div>

</body>
</html>
<script>

  // The JavaScript code for HTML diff goes here...

</script>

Answer №2

To simplify the comparison of HTML code strings, you can split the text into arrays of strings and compare them manually.

For instance, in tackling part 1 of your issue, you can compare words (string arrays) and introduce a span with the class highlightRed to change the background to red.

Here's an example to reference: https://codepen.io/vck3000/pen/xYeLKq/?editors=1111

//retrieve the strings
var div1Text = document.querySelector("#div1").innerHTML;
var div2Text = document.querySelector("#div2").innerHTML;

//split the strings
var div1TextSplitted = div1Text.split(" ");
var div2TextSplitted = div2Text.split(" ");

//variables to iterate through the split string
var wordNumber1 = 0;
var wordNumber2 = 0;

//new strings to reassign to the divs
var newDiv1Text = "";
var newDiv2Text = "";

//Part 1: Red highlight
while(true){
  //if a non-matching word is found
  if(div1TextSplitted[wordNumber1] !== div2TextSplitted[wordNumber2]){
    //insert a span
    newDiv1Text += "<span class='highlightRed'>" + div1TextSplitted[wordNumber1] + "</span> ";
    //increment the variables
    wordNumber2++;
    wordNumber1++;
  }
  //if the text matches
  else{
    //append the same text without changes
    newDiv1Text += div1TextSplitted[wordNumber1] + " ";
    //increment variables
    wordNumber1++;
    wordNumber2++;
  }

  //stop the loop if either string reaches the end
  if(div1TextSplitted[wordNumber1 + 1] === undefined || div2TextSplitted[wordNumber2 + 1] === undefined){
    break;
  }
}

//reassign the modified text to the div
document.querySelector("#div1").innerHTML = newDiv1Text;

Part 2 (yellow highlight) poses a similar challenge but is slightly more complex. Try to solve it on your own.

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

In what way does this closure cause componentDidUpdate to mimic the behavior of useEffect?

Recently, I came across an insightful article by Dan Abramov titled: A Complete Guide to useEffect. In the section that discusses how Each Render Has Its Own… Everything, two examples were provided. The first example demonstrates the usage of useEffect a ...

Can you target an 'input' field that is within a component conditionally rendered using 'v-if'?

Imagine this vue.js template code: <div v-if="y===0"> <input ref="textbox">{{textbox}}</input> </div> In the scenario where y is data retrieved asynchronously, Is there a way to direct focus to the 'input' element onc ...

Building a dynamic form in React: Fetching select data from an API, posting to another API, and automatically clearing fields upon submission

I am currently working on a form that utilizes a GET request to retrieve data from an API endpoint and then proceeds to make a POST request to another endpoint. Although I have been successful in achieving this function, I am facing challenges with reset ...

Having trouble retrieving the NextAuth session data within Next.js 12 middleware

I've been working on implementing route protection using Next.js 12 middleware function, but I keep encountering an issue where every time I try to access the session, it returns null. This is preventing me from getting the expected results. Can anyon ...

Populate the content of the child DIV to match the grid layout as a whole

I am attempting to control the layout of the grid on my website using CSS. By utilizing Bootstrap 4, I have created two divs with equal height using display:grid. However, I am facing difficulties in managing the child elements within these divs. I am tryi ...

Close the overlay by clicking outside of it

I'm working on creating a unique pop-up window that appears when a customer adds a product to their cart. The design features red and green background divs with a darker overlay (#overlay-daddy) and a white child div (#overlay). My issue arises from ...

"Exploring the world of jQuery and the array data structure

I'm attempting to target and access all inputs with the specified class: validate['number'] However, in some cases, the classes may appear as follows: validate['required', 'number'] My goal is to identify all elements ...

Tips on adding a date range selection or multi-date selection capability within a single Kendo calendar

Can a single Kendo calendar instance incorporate both date range selection and multi-date selection features? ...

The shadow feature in Three.js doesn't seem to be functioning properly

I'm having trouble getting the Three.js shadow effect to work in version r82. I believe I have everything set up correctly, but for some reason it's not working. Can anyone point out what I might be missing? Here is an example link for referen ...

Steps for creating a fixed menu bar that remains stationary while scrolling

I am facing three challenges: When I hover over my menu links, I want them to become 'bold', but it causes the items on the right to move slightly. How can I prevent this movement? In regard to the dropdown menu on "Two", how can I ensure t ...

Adjust the top margin of content to account for the height of a fixed header

When dealing with a fixed header that has been removed from the HTML flow, it can be tricky to adjust the content below it. The challenge arises because the height of the header can vary based on screen size. How can we dynamically adjust the margin-top fo ...

Counting words with JavaScript without using an input tag is a useful skill

Is there a way to count the words in a text using only p and span tags, without using input tags? How can this be achieved? <span class="word" id="word">Words Number</span> <p class="any" id="any"> ...

Looking for an image that spans the entire height of the container

I need help with positioning an img inside a div container that has a background color. I want the image to overlay on top of the div, extending beyond its height without causing any scroll bars. Here is a fiddle related to this issue: http://jsfiddle.net ...

What is the best way to prevent using a function expression in order to return a local variable within an AngularJS factory?

Is there a way to return "stories" by setting "vm.stories = storyDataAsFactory.stories" instead of the current method "vm.stories = storyDataAsFactory.stories()" ? I've tried various combinations without any luck. Additionally, it seems that I can cal ...

What is the method for programming a Discord bot to respond to your messages?

As a beginner in coding, I have been working on creating a bot that can respond with whatever is said after the command !say. For example - if you type !say hello, the bot will reply with "hello". This is what I have attempted: let args = message.content ...

"Ionic offers a seamless integration of both side menu and tabs for enhanced navigation

I am working on implementing a sidemenu and tabs on the same screen in my Ionic app project. Currently, it is almost working, but I need the bottom tabs to be visible at all times while also being able to navigate to other views from the sidemenu without ...

Tips for keeping the scrollbar permanently at the bottom in JavaScript?

I am trying to implement a feature where a div always scrolls down automatically. scrollDown(){ var chat = this.conversation; this.conversation.scrollTop = chat.scrollHeight; } checkKeyPress(e){ if (e.key == "Enter") { this.scrollDown(); .. ...

What is the jQuery equivalent for converting this JavaScript code?

Here's a code snippet that I am struggling with: data=>{document.querySelector( "#os11.html-widget.gauge svg text[font-size='10px'] tspan" ).innerHTML = data.text I attempted the following solution: $("#os11.html ...

What is the best way to refresh updated .js files directly from the browser console?

Is it possible to use RequireJS 2 to dynamically reload a recently updated .js file? Let me explain my scenario: I have a Backbone.js object named Foo with a function called Bar that currently displays an alert with "abc" when called; In my webpage, I ex ...

Updating CSS for dropdown menu in Fluent/Fabric design

I am working with a dropdown component from Fluent UI and I am trying to customize the CSS of the dropdown options. Although I can add classes using className to the dropdown itself, I am facing difficulty in styling the dropdown options directly due to th ...