1

how do I refresh a specific element in html using only vanilla javascript.

the goal is after adding an attribute to it with a value.

I will refresh the element.

Skeeith22
  • 186
  • 2
  • 16
  • Please post your code. Show us what are you trying to do. What is the desired result. – abhishekkannojia Nov 28 '16 at 06:26
  • 2
    you can use ajax call to get the content and update the specific element with a div ...this link could be helpful http://stackoverflow.com/questions/17886578/refresh-part-of-page-div – Geeky Nov 28 '16 at 06:26
  • thanks for the reply guys! :) but I don't want to use jQuery as I have said vanilla JavaScript only – Skeeith22 Nov 28 '16 at 22:12

1 Answers1

0

Libraries like React are built for this purpose. But we can sort of do it with pure Javascript too. Here's what we need to do:

  • delete the element with parent.removeChild(element)
  • create another one with document.createElement(element)
  • set the properties the way you want element.setAttribute(name, value)
  • add it to the parent element with parent.appendChild(newElement)

I have working example here in this link: https://codepen.io/edo9k/pen/poyRJJN?editors=1010

But you can also update the element directly, instead of 'refreshing' it. Which can be done with element.setAttribute or getting the attribute directly like a I do changing the font size of the element in line 20 of the example: elm.style.fontSize = counter + "pt";.

Your question lacks context, but depending on what you're trying to do, you should consider a library or some alternative method of updating this element. There might be security issues doing it like the way I'm proposing here, both by modifying attributes directly or by deleting/adding a new element.

You can find detailed explanation of all these API function in Mozilla's Web Docs: https://developer.mozilla.org/pt-BR/docs/Web/API

edo9k
  • 115
  • 1
  • 11