Add Elements to the Dom Given Plain Text HTML Using Only Pure JavaScript (No Jquery)

Add elements to the DOM given plain text HTML using only pure JavaScript (no jQuery)

Try assigning to the innerHTML property of an anonymous element and appending each of its children.

function appendHtml(el, str) {
var div = document.createElement('div');
div.innerHTML = str;
while (div.children.length > 0) {
el.appendChild(div.children[0]);
}
}
var html = '<h1 id="title">Some Title</h1><span style="display:inline-block; width=100px;">Some arbitrary text</span>';
appendHtml(document.body, html); // "body" has two more children - h1 and span.

How to select this text using pure javascript, no jquery?

var elem = document.getElementsByClassname("myClass")[0],
txtNode = elem.childNodes[0],
txtNodeValue = txtNode.nodeValue;
console.log(txtNodeValue);

Example.

We select the element by its class ([0] just tells it to select the first element in the matched set) and then look for its first child node. In your case this would be the text node, so all we have to do from there is get the nodeValue.

Creating a new DOM element from an HTML string using built-in DOM methods or Prototype

Note: most current browsers support HTML <template> elements, which provide a more reliable way of turning creating elements from strings. See Mark Amery's answer below for details.

For older browsers, and node/jsdom: (which doesn't yet support <template> elements at the time of writing), use the following method. It's the same thing the libraries use to do to get DOM elements from an HTML string (with some extra work for IE to work around bugs with its implementation of innerHTML):

function createElementFromHTML(htmlString) {
var div = document.createElement('div');
div.innerHTML = htmlString.trim();

// Change this to div.childNodes to support multiple top-level nodes.
return div.firstChild;
}

Note that unlike HTML templates this won't work for some elements that cannot legally be children of a <div>, such as <td>s.

If you're already using a library, I would recommend you stick to the library-approved method of creating elements from HTML strings:

  • Prototype has this feature built-into its update() method.
  • jQuery has it implemented in its jQuery(html) and jQuery.parseHTML methods.

How to get the pure text without HTML element using JavaScript?

[2017-07-25] since this continues to be the accepted answer, despite being a very hacky solution, I'm incorporating Gabi's code into it, leaving my own to serve as a bad example.

// my hacky approach:
function get_content() {
var html = document.getElementById("txt").innerHTML;
document.getElementById("txt").innerHTML = html.replace(/<[^>]*>/g, "");
}
// Gabi's elegant approach, but eliminating one unnecessary line of code:
function gabi_content() {
var element = document.getElementById('txt');
element.innerHTML = element.innerText || element.textContent;
}
// and exploiting the fact that IDs pollute the window namespace:
function txt_content() {
txt.innerHTML = txt.innerText || txt.textContent;
}
.A {
background: blue;
}

.B {
font-style: italic;
}

.C {
font-weight: bold;
}
<input type="button" onclick="get_content()" value="Get Content (bad)" />
<input type="button" onclick="gabi_content()" value="Get Content (good)" />
<input type="button" onclick="txt_content()" value="Get Content (shortest)" />
<p id='txt'>
<span class="A">I am</span>
<span class="B">working in </span>
<span class="C">ABC company.</span>
</p>

Appending html using native javaScript

Well, I know this works:

let elem = document.querySelector ( 'css-selector (id or class)' )

That should give you your element. Then you do this:

elem.innerHTML = elem.innerHTML + myNewStuff;

That'll append your html to the innerHTML of the element. I tried it quickly, it works.

How can I append HTML code using JavaScript?

Take a look at this original link for that code where we append to the DOM.
Then you can use string interpolation to add the variables to the code like below

function appendHtml(el, str) {  var div = document.createElement('div'); //container to append to  div.innerHTML = str;  while (div.children.length > 0) {    el.appendChild(div.children[0]);  }}
let author = "me";let message = "Message...";let time = "15:21";
var html = `<li><span class="author">${author}</span><span class="message">${message}</span><span class="time"><div class="line"></div>${time}</span></li>`;appendHtml(document.body, html);

How can get the text of a div tag using only javascript (no jQuery)

You'll probably want to try textContent instead of innerHTML.

Given innerHTML will return DOM content as a String and not exclusively the "text" in the div. It's fine if you know that your div contains only text but not suitable if every use case. For those cases, you'll probably have to use textContent instead of innerHTML

For example, considering the following markup:

<div id="test">
Some <span class="foo">sample</span> text.
</div>

You'll get the following result:

var node = document.getElementById('test'),

htmlContent = node.innerHTML,
// htmlContent = "Some <span class="foo">sample</span> text."

textContent = node.textContent;
// textContent = "Some sample text."

See MDN for more details:

  • textContent
  • innerHTML

Converting HTML string into DOM elements?

You can use a DOMParser, like so:

var xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";var doc = new DOMParser().parseFromString(xmlString, "text/xml");console.log(doc.firstChild.innerHTML); // => <a href="#">Link...console.log(doc.firstChild.firstChild.innerHTML); // => Link


Related Topics



Leave a reply



Submit