Cannot execute the function test()

I'm just diving into the world of JavaScript and have put together a little fiddle with my code. Check it out here.

However, I've run into an issue where removing CDATA makes it work fine in fiddle but causes problems in XHTML editors like Eclipse:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Below is a snippet of my JavaScript:

<![CDATA[
  function test() {
      alert(document.getElementById("divId"));
      var regex = new RegExp('this',"gi");
      document.getElementById("divId").innerHTML
      = document.getElementById("divId").innerHTML.replace(regex, 
            function(matched) 
            {
                return '<span class=\'highlight\'>' + matched + '</span>';
            });
  }
]]>

This is the <div> causing me trouble:

<div id="divId">
    This is the text This is the text This is the text This is the text 
    This is the text This is the text This is the the text
</div>

Unfortunately, I can't seem to call the test() function. Any advice on how to proceed?

Answer №1

To streamline your code, consider removing CDATA lines:

...
// <![CDATA[
...
// ]]>

Answer №2

Wrap the content in between /* */ like shown below

 /*<![CDATA[*/

            function sampleFunction(){
        alert(document.getElementById("specificId"));
         var regex = new RegExp('that',"gi");
         document.getElementById("specificId").innerHTML     
         =document.getElementById("specificId").innerHTML.replace(regex, function(matched) 
        {
            return '<span class=\'highlight\'>' + matched + '</span>';
        });


    }

/*]]>*/

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

Enhancing UI design with Vue.js

I'm attempting to customize elements using data from a JSON file in Vue.js: <div v-for="(item, index) in json._items" class="help-inner-callout" v-html="item.text" style="top:item.top; left: item.left;">&l ...

Incorporating external API information into Google Maps

My current challenge involves creating a polygon on Google Maps using data obtained from an external API found at . Upon analyzing the API response, the following information is provided: { "id": 28, "name": "Local spots", "description": "", "isprivate": ...

Promise-based React Redux Login: An error occurred during login process

I'm currently working on my first React+Redux application and I'm still in the scaffolding phase. As a newcomer to React, I've encountered an issue with my simple login app. The AuthAction returns a Promise from the login(username, password) ...

Does Vuejs have a counterpart to LINQ?

As a newcomer to javascript, I am wondering if Vue has an equivalent to LinQ. My objective is to perform the following operation: this.selection = this.clientsComplete.Where( c => c.id == eventArgs.sender.id); This action would be on a collect ...

Assign a CSS class to a DIV depending on the vertical position of the cursor

The website I am currently developing is located at Within the site, there is a collection of project titles. When hovering over a project title, the featured image is displayed directly below it. I would like to change the positioning of these images to ...

Using conditional rendering within the map function in React

I am working with the code snippet below and I am looking to implement a conditional rendering to exclude index 0 from being displayed. How can I achieve this? return ( <section> {pokemonCards.map((pokemon, index) => ...

Issue with Angular 2 pipe causing unexpected undefined result

Here is a JSON format that I am working with: [{ "id": 9156, "slug": "chicken-seekh-wrap", "type": "dish", "title": "Chicken Seekh Wrap", "cuisine_type": [2140] }, { "id": 9150, "slug": "green-salad", "type": "dish", "title": "Green Sala ...

The method by which AngularJS identifies the appropriate property within a return value

In Angular, watchers are utilized to identify property changes and trigger a listener function. An example of a watcher declaration is shown below: $scope.food = "chicken"; scope.$watch( function() { return food; }, function(newValue, oldValue) { ...

Partial View fails to render on the webpage

After submitting information from my first partial view, I attempted to load a second partial view. However, upon submission, the first partial view just refreshes and remains on the same page instead of loading the new view. Despite setting up my controll ...

Generate a c3 chart illustrating a bar graph incorporating offset and duration

How can I accurately display daily working hours for a person, using input data of date and duration worked in seconds? I am facing difficulty determining the offset for the duration displayed on the graph. For instance, if a person starts work at 9:30 am ...

What results can be expected from a piped file stream?

Perhaps the wording of the question may not be perfect, but here is some additional context. With GridFSBucket, I am able to store a file in MongoDB and retrieve a download stream for that file. Here's my query: If I wanted to send that file back as a ...

Javascript puzzle - I have 99 obstacles

...but a malfunction isn't one. Hey there, I am new to learning so I apologize for the seemingly simple question. I'm experimenting with a theoretical logic statement that would work using javascript. For instance: if (issues == 99) { malfunct ...

Enzyme's simulate() failing to produce expected results with onChange event

I am facing an issue with a component and its related tests: import React from 'react'; import PropTypes from 'prop-types'; function SubList (props) { var subways = ['', '1', '2', '3', & ...

Is it possible to retrieve JavaScript object properties using HTML elements?

I have fetched an array of objects using jQuery.getJSON(). Each object should be represented by an HTML div element, allowing users to click on the element and access all properties of the corresponding object. What is the most efficient approach for achie ...

Activating a tab using a JS call in Bootstrap with the data-toggle attribute

My JSP page is using bootstrap's data-toggle="tab" functionality to display tabs. When the page loads, one tab is made active by default. <ul class="nav st-nav-tabs"> <li class="active"><a href="#tab1" data-toggle="tab">First Ta ...

The attempt to load a JavaScript resource has resulted in an error: the file was not located, despite the fact that it is a

Recently, I came across a new challenge in my application. Whenever I navigate to specific pages, I notice an error message in the development console: inject.preload.js:373 GET blob:http://my-app-name.test/ba65127c-383e-45b7-8159-9b52ea288658 0 () Upon ...

What is the best way to configure AngularJS for optimal integration with Google Maps services and functionalities in an "angular way"?

I'm currently working on a new app that utilizes the Google distance matrix, directions service, and various map features such as custom markers. I'm curious - where do you think is the best place to house all of this different functionality? Sho ...

Guide to dynamically displaying different URLs based on checkbox selection using Ajax

My goal is to dynamically change the view of a page based on which checkbox is checked. Additionally, I want to ensure that when one checkbox is selected, another becomes unchecked. <input class="searchType" type="checkbox"></input> <input ...

Genvalidator: Validate forms by checking for checkbox selection

Currently, I am utilizing genvalidator to conduct tests on input fields within a form. One issue I am encountering is the inability to determine if a checkbox has been checked. Below are the settings for all fields: frmvalidator.addValidation("name","req ...

Converting API data in Angular using rxjs

Hey there, I received this response from an API: { "records":[ { "id":1, "motivazione":"", "autorizzazione":false, } ] } Can anyone help me transform it to loo ...