Comparing .innerHTML with createElement() | Exploring setAttribute() versus the Direct method*

Someone mentioned that this approach was not considered "proper", but I didn't pay much attention to it until I encountered a run-time error in IE9. Now, I need help converting the code to utilize object properties instead. What is the reason behind innerHTML being frowned upon as a best practice?

 var element = document.createElement('div');
  element.innerHTML = '<a name="a1" class="b" href="' + data[2].value + '">' + data[1].value + '</a>';

Answer №1

It's a bit unconventional to nest an A element within another A element, but the code below should do the trick.

let newLink = document.createElement('a');
newLink.name = "link1";
newLink.className = "link";
newLink.href = data[2].value;
newLink.appendChild(document.createTextNode(data[1].value));

This approach assumes that data[1].value may contain untrusted HTML content, making it a more secure option against cross-site scripting (XSS) attacks compared to using innerHTML.

Answer №2

Using innerHTML is crucial, but it seems like you may not be utilizing it correctly.

The innerHTML function targets the content within a tag, specifically what is encapsulated by opening and </a>

It is important to assign values to your d[2].value using setAttribute and only apply innerHTML to d[1].value

This code snippet should work fine (although untested)

  var c=document.createElement('a');
  c.setAttribute("href",d[2].value);
  c.setAttribute("name","a1");
  c.setAttribute("class","b");
  c.innerHTML = d[1].value;

For further clarification, refer to these resources on setAttribute functionality and innerHTML properties

Answer №3

It appears that you are generating a nested anchor by using document.createElement('a') in your code. This will result in HTML structure like this:

<a>
    <a href="www.google.com">Click Here</a>
</a>

This is not the correct way to create anchors, as using innerHTML for anchors can lead to issues. Instead, it is recommended to set attributes individually like this:

c.setAttribute('class', 'signature'); 
c.setAttribute('href', 'xyz');

You can also directly set attributes on the anchor element using JavaScript. For reference, check out http://www.w3schools.com/jsref/dom_obj_anchor.asp (Anchor object properties).

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

Prevent scrollbar from appearing while splash page loads

Looking for help with a script to create a splash/intro page loader. $(function(){ setTimeout(function() { $('#splash').fadeOut(500); }, 6000); }); The current script hides the intro page after 6 seconds, ...

Ways to expand the border horizontally using CSS animation from the middle

Currently, I am experimenting with CSS animation and I have a query regarding creating a vertical line that automatically grows in length when the page is loaded. I am interested in making the vertical line expand from the center in both upward and downwar ...

Issue with retrieving attributes in the directive

One of the challenges I encountered is incorporating a directive that wraps the jQuery FullCalendar plugin into my project. Here is how I implement the directive: <div sg-calendar format-column-header-month='dddd' format-co ...

Efficiently organizing dates in the Vuetify date range picker

I am working with a vuetify date range picker component and have the following code: <v-menu ref="effectiveDateMenu" v-model="effectiveDateMenu" :close-on-content-cl ...

Removing a function when changing screen size, specifically for responsive menus

$(document).ready(function () { // retrieve the width of the screen var screenWidth = 0; $(window).resize(function () { screenWidth = $(document).width(); // if the document's width is less than 768 pixels ...

It can be challenging to manage numerous if-else conditions in JQuery

I am having trouble with my JQuery code that checks multiple conditions. No matter what I enter, it always goes to the else condition. $(function() { $('#installment').on("keydown keyup", check); function check() { var inst = Number($( ...

"Uncovering the parent element with jQuery: A step-by-step guide

I need help increasing the font size of a parent element without affecting the entire body's font size. How can I achieve this? For example, with the id="vs-1", I want to increase the font size of the grandparent li text here which is "1940". $("li ...

Generating a fresh array of unique objects by referencing an original object without any duplicates

I can't seem to figure out how to achieve what I want, even though it doesn't seem too complicated. I have an array of objects: { "year": 2016, "some stuff": "bla0", "other stuff": 20 }, "year": 2017, "some stuff": "bla1", ...

javascript with a focus on objects

Having trouble with the scene.add(Obj); line for my object player1. I keep getting an error saying that Obj does not exist: function Player(x, y, z) { this.Speed = 0; this.AngleAcc = 0; this.Angle = 0; this.X=x; this.Y=y; this.Z=z; this.MaxSpeed = ...

Is it possible that bitwise left shifts in JavaScript ES6 (<<) become cyclical after surpassing a shift of 63?

From my understanding of the << bitwise left operator in JS (ES6), the void to the right is typically filled with zeros. However, through observation in both V8 and JSC, it appears that the set bits suddenly reappear when we shift by 64 or more. (2 ...

Leveraging the power of JavaScript to retrieve data from BigQuery

Having just started my journey with JavaScript and Google BigQuery, I am seeking help due to my lack of experience in these areas. My goal is to create a javascript code that can fetch data from one of the public databases on BigQuery. I came across a solu ...

Is it better to have Angular and Laravel as separate applications or should Laravel serve the Angular app?

I have a new project in the works, aiming to create a large SAAS application. Although I come from a CakePHP background, I've decided to use Laravel and Angular for this venture. As I navigate through unfamiliar territory with these technologies, I a ...

Having issues with angular-file-upload failing to include the file in the request

I am currently using angular-file-upload in order to upload an image to a server that is utilizing Node and Express 4.0. However, I am encountering difficulties in accessing the file data on the server. Below is the relevant code snippet: <input type= ...

How to make Angular 5 wait for promises to finish executing in a for loop

My task involves working with an array like this: arr = ['res1', 'res2', 'res3']; For each value in the arr, I need to make an API call that returns a promise. arr.forEach(val => this.getPromise(val)); The getPromise me ...

Utilizing an Array of objects in conjunction with $.when

I have a list of Ajax requests stored in an Array, and I need to wait for all of them to finish loading before processing the results. Here is the code snippet I am currently using: $.when( RequestArray ).done(function(){ this.processResu ...

The functionality of item.classList.toggle() in HTML+CSS+JS fails to execute

I have been working on a program that aims to flip a card when it is clicked. The JavaScript code I have written for this functionality is as follows: /* Card flipping onclick */ import "./Stylesheets/FlipCardStyle.css" var cards = document.quer ...

Failing to catch the return value from a stored procedure in ASP Classic

Apologies for the lengthy post, but I wanted to provide all the necessary details. I am facing an issue with a JavaScript function that uses ajax to call some asp code, which then executes a stored procedure to check if a record already exists. Depending ...

Transfer results of SQL query from PHP to JavaScript array

Every day, I manually update a JavaScript variable in the following way: <script> var data = [ ['Austria','IBM','8284927','UF93NV', '10'], ['Spain','Dell&ap ...

Accessing a peaceful API and displaying the outcome on a webpage using Node.js

I am currently working on a project that involves fetching data from a RESTful API and displaying the results on an HTML webpage using Node.js. While my code is running smoothly, I would like to ensure that the RESTful request is made every time the webp ...

Arrays data being retrieved and set by Chrome Extension are visible in the console but not appearing in the HTML

Having trouble displaying my arrays in HTML. I'm attempting to do this within a Chrome Extension. While I can view the array perfectly in console.log, I'm encountering issues when trying to add it to the HTML DOM: /* Generating the array f ...