You are limited to using a maximum of two custom tags within a custom div

I came up with this code that is supposed to style the elements differently based on their tag names. However, when I tested it, the styling did not work as expected. For example, 'London' should be displayed as a large and bold h1 text, while the other two should be h2 texts. But instead, everything shows up as normal text. Additionally, if I use only two elements in the weather-app, they display correctly, but adding more than two causes issues. Another problem I noticed is that when using the same element name twice, only the first instance gets styled properly, while the second appears as regular text. I'm seeking help in identifying and fixing these issues. Any advice or guidance would be greatly appreciated. Thank you!

Answer №1

It seems like this solution may fit your needs. The issue appears to be related to the shadow.appendChild(). Consider using shadow.host instead.

const h1 = (tag) => {
  const ptag = document.querySelector(tag);
  const shadow = ptag.attachShadow({
    mode: 'open'
  });
  const h1 = document.createElement('h1');
  h1.innerHTML = ptag.innerHTML;
  shadow.host.parentNode.replaceChild(h1,shadow.host);
}

Additionally, replace .appendChild() with .replaceChild().

Check out the Demo below:

const h1 = (tag) => {
  const ptag = document.querySelector(tag);
  const shadow = ptag.attachShadow({
    mode: 'open'
  });
  const h1 = document.createElement('h1');
  h1.innerHTML = ptag.innerHTML;
  h1.style.color = "blue";
  shadow.host.parentNode.replaceChild(h1,shadow.host);
}
const h2 = (tag) => {
  const ptag = document.querySelector(tag);
  const shadow = ptag.attachShadow({
    mode: 'open'
  });
  const h2 = document.createElement('h2');
  h2.innerHTML = ptag.innerHTML;
  shadow.host.parentNode.replaceChild(h2,shadow.host);
}
const div = (tag) => {
  const ptag = document.querySelector(tag);
  const shadow = ptag.attachShadow({
    mode: 'closed'
  });
  const div = document.createElement('div');
  div.innerHTML = ptag.innerHTML;
  shadow.host.parentNode.replaceChild(div,shadow.host);
}
h1('city-name');
h2('we-data');
h2('temp-data');
h1('city-name');
div('weather-app');
<weather-app>
  <city-name>London</city-name>
  <we-data>Rains</we-data>
  <temp-data>15 C</temp-data>
  <city-name>Hi. Does thhis look like h1 text?</city-name>
</weather-app>

Answer №2

  1. To achieve the desired outcome, consider utilizing shadow.host and replaceChild(), as suggested in a previous response by @Carsten Løvbo Andersen.
  2. .querySelector() retrieves the first matching element, while .querySelectorAll() gathers all matches, necessitating the use of .querySelectorAll().
  3. The functions for h1, h2, and div share notable similarities - here's an adjusted version:

const foo = (elementTag, shadowMode) => tag => {
  const query = document.querySelectorAll(tag);
  query.forEach(ptag => {
    const shadow = ptag.attachShadow({
      mode: shadowMode
    });
    const element = document.createElement(elementTag);
    element.innerHTML = ptag.innerHTML;
    shadow.host.parentNode.replaceChild(element, shadow.host);
  });
};

const h1 = foo('h1', 'open');
const h2 = foo('h2', 'open');
const div = foo('div', 'closed');

h1('city-name');
h2('we-data');
h2('temp-data');
div('weather-app');
<weather-app>
  <city-name>London</city-name>
  <we-data>Rains</we-data>
  <temp-data>15 C</temp-data>
  <city-name>Hi. Does this resemble h1 text?</city-name>
</weather-app>

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

Is there a way to execute a javascript function that is located outside of my Angular application without having to import it?

I need to be able to trigger a JavaScript function that is located outside of my Angular app when a button is clicked. Unfortunately, it seems that importing the JavaScript directly into my Angular app isn't feasible for this task. The platform I am ...

What is the best way to right-align a label in a vertical MUI Slider in ReactJS?

I am currently working with ReactJS/TS and MUI (Material-UI) to develop a vertical slider that requires the label to be positioned on the right side. By default, MUI places the label on the left for vertical sliders. I have reviewed the API documentation e ...

Having trouble making jQuery code disable input field based on checkbox status

Is there a way to automatically disable the price input field once the checkbox is checked and clear any existing text? I seem to be having trouble with my current code.. <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <scr ...

Choose ng-change within the table

I've searched everywhere for an answer to this, but I couldn't find it. I have a table that contains select and date input fields. <table id="tblCorrAction" class="table table-bordered table-striped table-hover table-condensed"> <t ...

Modify the appearance of an element within an array upon selection by comparing it with a separate array

In my code, there is an array called tagList that contains a list of objects. When one of these objects is clicked on, it gets added to another array named selectedTags. var selectedTags = []; export default class RegisterTags extends Component { con ...

Issue with border radius not applied to input-group in Bootstrap 3

Can anyone explain why the input-group in Bootstrap 3.4 is missing all border radius? <form action="{{ route('dashboard.users.index') }}" method="get"> <div class="input-group"> <input type="text" name="search" class="f ...

Material UI in React: A lengthy typography body necessitates a line break

Currently using the Material UI grid system to create two columns side by side. However, due to the Lorem ipsum text length, the right column is pushed down to a new row. Shortening the text will allow it to be displayed properly in two columns. <Grid c ...

Foundation 5 - ensure background-image covers the entire column width

I'm trying to achieve a unique layout using Zurb Foundation. My goal is to have two columns, each taking up half of the screen: <div class="small-6 columns"><!-- INSERT IMAGE HERE --></div> <div class="small-6 columns"> < ...

Is there a way to alter a class using ng-class only when the form is deemed valid?

I am trying to implement a feature where an input field shows as required, but once the user enters text, it indicates that the input is valid by changing the border color from red to green. I am facing an issue with this line of code always returning fal ...

Error in browser caused by JQuery JavaScript, not Dreamweaver

I need help creating a webpage that can extract and display recent earthquake data based on user input location on Google Maps. I have been using Dreamweaver to test my code, and everything functions perfectly when I use the live webpage feature within th ...

What is the method for implementing type notation with `React.useState`?

Currently working with React 16.8.3 and hooks, I am trying to implement React.useState type Mode = 'confirm' | 'deny' type Option = Number | null const [mode, setMode] = React.useState('confirm') const [option, setOption] ...

Servlet unable to retrieve parameters from Form due to unexpected NULL values

Here is a basic form element for you to review: <form action="Test" method="POST" enctype="multipart/form-data"> <input type="text" name="first_name" title="First Name"></input> <input type="text" name="last_name" title="Las ...

typescript error is not defined

While browsing online, I came across a post discussing how to transfer data from an MVC model to a .ts file. The suggestion was to include the following code: <script type="text/javascript"> var testUrl = @Html.Raw(Json.Encode(Model.testUrl) ...

Buttons are not aligned with the rest of the row's height

I'm currently working on designing an upload layout that consists of a container with a row inside. Within the row, there are two buttons (each containing input elements) and one h3. For some reason, I am having difficulty getting them to align at the ...

Using javascript to dynamically change text color depending on the selected item

I am currently working on a website for a snow cone stand and I want to incorporate an interactive feature using JavaScript. Specifically, I would like to color code the flavor list based on the actual fruit color. The flavor list is already structured i ...

The validation feature is ineffective when used with Material UI's text input component

I need a function that can validate input to make sure it is a number between 1 and 24. It should allow empty values, but not characters or special symbols. function handleNumberInput(e) { const re = /^[0-9\b]+$/; const isNumber = re.test(e.target.val ...

Error encountered in loop for concatenating html elements: identifier unexpectedly found (jquery + html + php)

I am attempting to concatenate HTML inside a variable within a loop and then return it populated. However, I am encountering an error: Uncaught SyntaxError: Unexpected token += in my code. <a style="cursor: pointer" id="addmore">More Entree ?</ ...

Ways to display the page's content within a div container utilizing Jquery

I am attempting to display the content of a URL page (such as ) within a <div> using JQuery, but so far I have been unsuccessful. Here is an example of what I am trying to achieve: <div id="contUrl"> .. content of google.fr page </div> ...

Is there a way to apply padding to a div element that has a display property set to table-cell?

I am trying to achieve a design where I have an image and a div containing vertically centered text. The div should have padding around it along with a border, similar to this example: https://i.sstatic.net/VlgIY.png Currently, this is the closest I have ...

Looking to transition from Node.js version v4.4.5 to v6.11.0 on your Windows system?

npm cache clean npm update -g I attempted upgrading using the provided commands, but unfortunately, the update did not go through as expected. Seeking advice for a successful update process. (Currently on Node.js 4.4.5 and aiming to upgrade to Node.js 6. ...