Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add a button using javascript to an existing DIV

Tags:

javascript

On my page I have:

 <div id='something'></div>

and I want to append this type of 'button' to it using JS:

<a href="/news_events/"><span class="picon-p-add-news"></span>Read more news</a>

I tried to use document.createElement but I'm not sure how to make it not just append it as text. How do I do this ?

like image 340
Mike Q Avatar asked Apr 13 '18 15:04

Mike Q


2 Answers

Something like this, where you can pass your element ID and URL through function arguments.

<!DOCTYPE html>
<html>
 <head>
  <script>
   function appendButton(elementId, url){
	var buttonEl = document.createElement("a");
	buttonEl.href = url;
	var buttonTextEl = document.createElement("span");
	buttonTextEl.className = "picon-p-add-news";
	buttonTextEl.innerText = "Read more news";
	buttonEl.appendChild(buttonTextEl);
	document.getElementById(elementId).appendChild(buttonEl);
   }
  </script>
 </head>
 <body>
   <div>    
    <button id="button">Click to add</button>
    <div id='something'></div>
   </div>
   <script>
      document.getElementById("button").addEventListener('click', () => appendButton("something", "/news_events/"));
   </script>
 </body>
</html>
like image 105
Avet Brutyan Avatar answered Nov 05 '22 02:11

Avet Brutyan


Use document.createElement to create the specified HTML elements. Then you can append those to your #something root element using Node.appendChild function. You can also use Element.innerHTML to gets or sets the HTML markup contained within the element.

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node.

const something = document.getElementById('something');

// creating the span element, then add a class attribute
const span = document.createElement('span');
span.setAttribute('class', 'picon-p-add-news');
span.innerHTML = 'span'; // some text to improve visualization

// create the anchor element with the href attribute
const a = document.createElement('a');
a.setAttribute('href', '/news_events/');

// append the span element inside the <a>
a.appendChild(span);
a.innerHTML += 'anchor'; // add extra text for display

// add the <a> element tree into the div#something
something.appendChild(a);
#something {
  border: 1px solid;
  text-align: center;
  font-size: 2rem;
}
#something > a {
  padding: 8px;
}
.picon-p-add-news {
  background: red;
  padding: 0 4px;
}
<div id="something"></div>
like image 23
Carloluis Avatar answered Nov 05 '22 02:11

Carloluis