Reputation: 1
I am working on a demo webpack app and there is a function that I have imported to my index.js
file which is returning a div element with some text inside of it.
The app starts with a component function that is appending a button. The button has an event listener which has an append method in its body.
The append method within the event listener has a function call passed as a parameter which returns the div element that I would like to put up on the page.
The function has a console.log within its body and this log shows the div element, but the element does not append and there are no errors in the console to tell me why it isn't being appended.
Would someone be able to explain why this code doesn't append the element to the DOM please?
index.js
import _ from 'lodash';
import searchPage from './search.js'
import './index.css';
function component() {
const button = document.createElement('button')
button.classList.add('button')
button.textContent = 'click me'
return button;
}
document.body.appendChild(component());
function searchPageComponent() {
document.body.remove()
const searchPageVar = searchPage()
console.log(searchPageVar)
return searchPageVar
}
const button = document.querySelector('.button')
button.addEventListener('click', () => {
document.body.appendChild(searchPageComponent())
})
search.js
export default function searchPage() {
const stockSearchPage = document.createElement('div')
stockSearchPage.setAttribute('id', 'search')
stockSearchPage.innerHTML = 'Search Page'
console.log('search for stocks')
return stockSearchPage
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: {
index: './src/index.js',
print: './src/search.js',
},
devtool: 'inline-source-map',
devServer: {
static: './dist',
},
plugins: [
new HtmlWebpackPlugin({
title: 'Webpack-demo',
}),
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
publicPath: '/',
},
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
},
],
},
optimization: {
runtimeChunk: 'single',
},
};
Click me button
Missing div *appears in console with no errors as to why not appended to the page
Upvotes: 0
Views: 38
Reputation: 1
I think you are calling searchPageComponent() somewhere and it is removing your body components. Please check it once. Because it is removing the whole body.
Upvotes: 0