Javascript, or other way, to delete a certain line of the html code, and create another in the same location as the previous one

Asked

Viewed 54 times

0

I need to know if there is a function that selects a specific line of code HTML to delete it, when to fire the function, and something to create a new line of code in the same place gives erased line, kind of to replace even.

OBS: It’s literally just a line of code :)

  • 1

    What do you mean by line? Could you put an example ?

  • You want to delete a text/content or you want to delete an HTML element?

1 answer

1

HTML consists of elements of GIFT (Document Object Model) and not by lines. It is represented by a tree nodes, where a node can be selected and modified via script (e.g., Javascript). Each node has a hierarchical position within the tree. What you need to do is know the position of the element you want to manipulate.

For example, if there are several elements <p> (paragraph) in HTML, each has an index (index) in the tree (also has a parent element, may have sibling elements and even child elements).

All page elements have a grandfather and a father: <html> and <body>, respectively.

If the element you want to modify has one id, it is much easier to select it, because a id is unique on the page and you can go right to him without worrying about his position in the tree.

The example below shows the replacement of a paragraph <p> by a link <a>:

function funcao(){
   
   // apagar e substituir o primeiro parágrafo <p>
   // por um link <a>
   var el = document.querySelectorAll("p")[0]; // seleciono o primeiro <p>
   var a = document.createElement("a"); // crio o elemento <a>
   var t = document.createTextNode("Novo link"); // crio o texto do <a>
   a.appendChild(t) // adiciono o texto no <a>
   a.setAttribute("href","pagina.html"); // adiciono href no <a>
   el.parentNode.insertBefore(a, el.nextSibling); // insiro o novo elemento <a> após o <p>
   el.outerHTML = ''; // apago o <p>
   
}
<h2>Lorem Ipsum</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed laoreet odio at interdum euismod. Praesent suscipit tortor ex, vel vestibulum eros rhoncus eu. Phasellus efficitur dui ut tincidunt eleifend.</p>
<p>Nullam finibus facilisis risus, nec vehicula tortor efficitur a. Suspendisse at nibh elementum elit volutpat fermentum vel a eros. Vestibulum at condimentum nisi.</p>
<input type="button" onclick="funcao()" value="Clique aqui para substituir">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.