Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
how to skip 1st argument but give 2nd argument in JavaScript

This createHtmlElement() function will by default create a <div> tag in body with nothing as content dynamically. But if the user does not provide parentId argument and skips to elementName parameter by using a comma (like this { createHtmlElement("", "div", "hello", "append") }) then it says: "Uncaught DOMException: Failed to execute 'querySelector' on 'Document': The provided selector is empty."

function createHtmlElement(parentId = "body" , elementName = "div", elementContent = "", choice ="append"){

            let parent = document.querySelector(`${parentId}`) || document.body; //parent element (parentId)
            let newElement = document.createElement(`${elementName}`)//created element (newElementName)
                newElement.textContent = `${elementContent}`;//element content (newElementContent)
            console.log(parent)
            console.log(newElement)
            parent.appendChild(newElement);
        }

        createHtmlElement("body" , "h2", "this is h2 tag")//this works totally fine
        createHtmlElement("", "h2","this is h2 tag")// console says the provided selector is empty

Please tell me how can i give a functionality that if i do not give 1st argument but i can give 2nd argument and the function executes normally. because if create 20 or 30 tags and writing "body" in each line it is time consuming and also space consuming how can i skip the first argument and give value of 2nd argument?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Move parentId the end, then you can omit it

function createHtmlElement(elementName = "div", elementContent = "", choice = "append", parentId = "body") {

  let parent = document.querySelector(`${parentId}`) || document.body; //parent element (parentId)
  let newElement = document.createElement(`${elementName}`) //created element (newElementName)
  newElement.textContent = `${elementContent}`; //element content (newElementContent)
  console.log(parent)
  console.log(newElement)
  parent.appendChild(newElement);
}

createHtmlElement("h2", "this is h2 tag", "body") //this works totally fine
createHtmlElement("h2", "this is h2 tag") // now it works

If you do not want to move it, you need to pass undefined. Please note null will not work

function createHtmlElement(parentId = "body", elementName = "div", elementContent = "", choice = "append") {
  console.log(parentId)
  let parent = document.querySelector(`${parentId}`) || document.body; //parent element (parentId)
  let newElement = document.createElement(`${elementName}`) //created element (newElementName)
  newElement.textContent = `${elementContent}`; //element content (newElementContent)
  console.log(parent)
  console.log(newElement)
  parent.appendChild(newElement);
}

createHtmlElement("body", "h2", "this is h2 tag", "body") //this works totally fine
createHtmlElement(undefined, "h2", "this is h2 tag") // now it works

Alternatively pass an object and spread

function createHtmlElement(parms) {
  const { parentId, elementName, elementContent, choice } = parms;
  
  let parent = document.querySelector(`${parentId || "body"}`); // if passed use parentId
  let newElement = document.createElement(`${elementName}`) //created element (newElementName)
  newElement.textContent = `${elementContent}`; //element content (newElementContent)
  console.log(parent)
  console.log(newElement)
  parent.appendChild(newElement);
}

createHtmlElement({"parentId": "body", "elementName":"h2", "elementContent": "this is h2 tag"}) 
createHtmlElement({"elementName":"h2", "elementContent": "this is h2 tag"}) 

about 4 years ago · Juan Pablo Isaza Relatório

0

You can simply pass undefined to skip an argument for JavaScript:

function createHtmlElement(parentId = "body", elementName = "div", elementContent = "", choice = "append") {
  console.log(parentId)
}

createHtmlElement(undefined, "h2", "this is h2 tag")

about 4 years ago · Juan Pablo Isaza Relatório

0

add below line one the first line of your createHtmlElement function.

if(!parentId){
  parentId = "body"
}

function createHtmlElement(parentId = "body", elementName = "div", elementContent = "", choice = "append") {
  if (!parentId) {
    parentId = "body"
  }

  let parent = document.querySelector(`${parentId}`) || document.body; //parent element (parentId)
  let newElement = document.createElement(`${elementName}`) //created element (newElementName)
  newElement.textContent = `${elementContent}`; //element content (newElementContent)
  console.log(parent)
  console.log(newElement)
  parent.appendChild(newElement);
}

createHtmlElement("", "h2", "this is h2 tag") // console says the provided selector is empty

However, I would suggest you to change your argument to an object instead of multiple arguments:

function createHtmlElement(options) {
  if(!options){ 
    throw new Error("options is missing")
  }
  let parentId = options.parentId || "body" 
  let elementName = options.elementName
  let elementContent = options.elementContent 
  let choice = options.choice
  // following by your logics
}

So when you call the function, you can simply do like this instead of enter empty string:

createHtmlElement({
  parentId: "body" , //just remove this property if you don't want to do this step
  elementName: "div",
  elementContent: "",
  choice: "append
})

This helps you to recognize which argument is for what purpose when you calling the function, especially when you want to use it for so many times, in the future you may forgot the 2nd or 3rd argument is for what purpose then you have to keep scroll back to the function to check what the purpose of argument.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda