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

0

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

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

    
asked by anonymous 08.02.2018 / 18:42

1 answer

1

HTML is made up of elements of DOM ( Document Object Model ) and not by lines. It is represented by a tree node, where a node can be selected and modified via script (eg JavaScript). Each node has a hierarchical position within the tree. What you need to do is know what position of the element you want to manipulate.

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

  

All elements of the page have a grandfather and a parent: <html> and <body> ,   respectively.

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

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

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">
    
08.02.2018 / 20:09