HTML, Javascript: Append a new element to the current empty element - javascript

How can I check if an element has a content (except whitespaces) then append a new element if the element has no content? Just pure javascript if possible.
<div id="container">
</div>
if the container has only whitespaces then:
<div id="container">EMPTY</div>
VS
<div id="container">I am not empty</div>
if the container has content (no need to append EMPTY):
<div id="container">I am not empty</div>

how to check for emptiness
var isEmpty = !document.getElementById("container").innerText.trim();
how to append
if(isEmpty) document.getElementById("container").innerText = "EMPTY";

You could check to see if the trimmed innerHTML is the empty string:
document.querySelectorAll('div').forEach(div => {
if (div.innerHTML.trim() === '') div.textContent = 'Empty';
});
<div></div>
<div>
</div>
<div>I am not empty</div>

Like so:
var checkDivs = () => {
document.querySelectorAll('#container').forEach((el)=>{
el.innerText = (el.innerText) ? el.innerText:'EMPTY';
})
}
checkDivs();
<div id="container">
</div>
if the container has only whitespaces then:
<div id="container">EMPTY</div>
VS
<div id="container">I am not empty</div>
if the container has content (no need to append EMPTY):
<div id="container">I am not empty</div>

Related

How to add an HTML element found by ID to the body?

I want to add an DOM element that is found by ID into the body tag and remove all ewxisting body nodes.
My solution does not work:
var ele = document.getElementById("email");
document.body.innerHTML = ele;
This:
document.body.innerHTML = ele;
Will interpret ele as a string and write that string to the document body. That string is going to be something like "[object HTMLDivElement]" (may differ by browser).
and remove all ewxisting body nodes
It sounds like you're looking for document.body.replaceChildren() then? For example:
var ele = document.getElementById("email");
document.body.replaceChildren(ele);
<div>test 1</div>
<div id="email">test 2</div>
<div>test 3</div>
There are a few options.
Option 1 : clear the content of <body> and append your element as a child.
var el = document.getElementById("one");
document.body.innerHTML = ''; // Clears the body inner HTML
document.body.appendChild(el) // Appends your element as a child
<div id="one">
HELLO
</div>
GOOD BYE CONTENT
Option 2 : Replace children of <body> with your element.
var el = document.getElementById("one");
document.body.replaceChildren(el); // Replace the body content by your element
<div id="one">
HELLO
</div>
GOOD BYE CONTENT
With append or replaceChildren you can reach this.
const tag = document.querySelector('#email');
const w = document.createElement('div');
w.append(tag)
document.querySelector('body').innerHTML = '';
document.querySelector('body').append(w);
<html>
<head>Head</head>
<body>
<h1>body</h1>
<div id="email"> EMAIL </div>
</body>
</html>
const tag = document.querySelector('#email');
document.querySelector('body').replaceChildren(tag);
<html>
<head>Head</head>
<body>
<h1>body</h1>
<div id="email"> EMAIL </div>
</body>
</html>

how to replace html tag in jquery without replace content?

I wonder how to change the HTML tag without replacing the contents. I did something like this:
$('#test > span').replaceWith('<div>' + $('#test > span').html() +'</div>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">
<span>hello</span>
<span>hello2</span>
<span>hello3</span>
</div>
Works, but still displays the first value (look code snippet). I think I need to merge .replaceWith() with $(this) but I can't quite do it.
To do what you require you can pass a function to replaceWith(). This function accepts two arguments, the index of the current element and its content, and returns the new element to make the replacement. As such you can use the second argument to change the parent tag while keeping the same content, like this:
$('#test > span').replaceWith((i, content) => `<div>${content}</div>`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">
<span>hello</span>
<span>hello2</span>
<span>hello3</span>
</div>
You could also use a RegExp to replace all <span></span> with <div></div> in the innerHTML:
// jQuery version
$('#btnReplaceHTML').click(() => {
const re = /(<\/?)span(>)/gm
$('#test').html($('#test').html().replace(re, '$1div$2'));
})
/*
// "Vanilla" JavaScript version
document.getElementById('btnReplaceHTML').addEventListener('click', () => {
const re = /(<\/?)span(>)/gm
const elem = document.getElementById('test');
elem.innerHTML = elem.innerHTML.replace(re, '$1div$2');
});
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">
<span>hello</span>
<span>hello2</span>
<span>hello3</span>
</div>
<button id="btnReplaceHTML">replace HTML</button>

javascript replace node and all of it childs with anothe code

How can you replace HTML tag with all tags branching inside using Javascript with other HTML code?
example:
<div class="a">
<div class="sub-a1">
<div class="sub-a12">
</div>
</div>
<div class="sub-a2">
<div class="sub-b">
</div>
</div>
I wanna replace all tags from tag div class 'a' including all sub nodes with another code.
is that's possible?
please help me.
const target = document.querySelector(".a");
target.innerHTML = //place your html here as string
Yes, this is possible. If you want to keep the div.a elements and just change the "subnodes" you have to use innerHTML in stead of outerHTML.
const divs = [...document.getElementsByClassName("a")]; //make a copy of the HTML collection so that they can be removed without being removed in the array
const newElement = "<h1>Replaced Element</h1>"; //this is your replacement element
for (let i = 0; i < divs.length; i++) { // loop through all the divs
divs[i].outerHTML = newElement; // set the outer html for the div to the replacement elemzent
}
You can do with .replaceWith() with a valid HTML code.
function replace() {
var para = document.createElement("P"); // Create a <p> element
para.innerText = "This is a paragraph"; // Insert text
document.querySelector(".a").replaceWith(para);
}
<div class="a">
<div class="sub-a1">
<div class="sub-a12">
<h4>Sample content1</h4>
</div>
</div>
<div class="sub-a2">
<div class="sub-b">
<h4>Sample content2</h4>
</div>
</div>
</div>
<button onclick="replace();"/>Click to Replace</button>

How can I get h1 innerText in JavaScript without the innerText of its child?

I want to get the innerText of <h1> without the innerText inside the span... this is the HTML of page:
var title = document.querySelector('div.col-md-8.info-header h1');
title = title && title.innerText;
console.log(title);
<div class="col-md-12 header">
<div class="col-md-8 info-header">
<h1> This note is for h1 tag!!!!!! <span> this note is insidespan v226hql!!! </span>
</h1>
</div>
</div>
but this will return the innerText of both <h1> and <span>.
what can I do?
Once you select the parent, you'll have to select its child text node, and get the contents of that node:
const h1 = document.querySelector('div.col-md-8.info-header h1');
const text = h1.childNodes[0].textContent;
console.log(text);
<div class="col-md-12 header">
<div class="col-md-8 info-header">
<h1> This note is for h1 tag!!!!!! <span> this note is insidespan v226hql!!! </span>
</h1>
</div>
</div>
Unfortunately there's no way to navigate directly to a text node with a query string, so you have to go through the childNodes first.
Try this.
var mainElement = document.getElementById("id_of_h1"),
innerElements = mainElement.firstChild,
innerTexts = [];
while (innerElements) {
if (innerElements.nodeType == 3) {
innerTexts.push(innerElements.data);
}
innerElements = innerElements.nextSibling;
}
var finalResult = innerTexts.join("");
finaresult will contain the intertext of the top element only.
In case you have <h1>hello <span>another</span> world and need to get all text except html elements- hello world not hello another world,then you need to this way
const h1 = document.querySelector('div.col-md-8.info-header h1');
const el = h1.childNodes;
let result = "";
for(i=0;i<el.length;i++){
if(el[i].nodeName == '#text'){
result+=el[i].textContent;
}
}
console.log(result);
<div class="col-md-12 header">
<div class="col-md-8 info-header">
<h1> This note is for h1 tag!!!!!! <span> this note is insidespan v226hql!!! </span> extra text without tag
</h1>
</div>
</div>

Modifying DOM of a webpage

The structure of a webpage is like this :-
<div id='abc'>
<div class='a'>Some contents here </div>
<div class='b'>Some other contents< </div>
</div>
My aim is to add this after the class a in above structure.
<div class='a'>Some other contents here </div>
So that final structure looks like this :-
<div id='abc'>
<div class='a'>Some contents here </div>
<div class='a'>Some other contents here </div>
<div class='b'>Some other contents< </div>
</div>
Can there be a better way to do this using DOM properties. I was thinking of naive way of parsing the content and updating.
Please comment if I am unclear in asking my doubt !
Create the desired element, give it the desired attributes, children, innerHTML, etc, and then append it:
var parent = document.getElementById('abc'),
ele = document.createElement('div');
ele.setAttribute('class', 'a');
ele.innerHTML = "Some other contents here";
parent.appendChild(ele);​
Fiddle
You can be lazy and just set the innerHTML of #abc, but in my opinion this method is more flexible.
I think this is what you are looking for http://jsfiddle.net/cExRS/
The code is this one
element = document.getElementById('abc');
element.innerHTML = "<div class='a'>Some other contents here </div>" + element.innerHTML;
You should really try jquery, it makes things a lot easier
Liked pointed out there's answer for prepending, Insert sibling node in JS
and How can I implement prepend and append with regular JavaScript?
<html>
<head>
<script type="text/javascript">
function add(myClass) {
var root = document.getElementById('abc');
var last = null;
for (var i = 0; i < root.childNodes.length; i++) {
var child = root.childNodes[i];
if (!child.className) continue;
var pat = new RegExp(myClass,'g');
var m = pat.exec(child.className);
if (!m) {
if (!last) continue;
var div = document.createElement('div');
div.appendChild(document.createTextNode('After A content'));
root.insertBefore(div, last.nextSibling);
break;
}
last = child;
}
}
</script>
</head>
<body>
<div id='abc'>
<div class='d'>Some contents here </div>
<div class='b'>Some other contents </div>
<div class='a'>Content A</div>
<div class='a'>Content A1</div>
<div class='a'>Content A2</div>
<div class='a'>Content A3</div>
<div class='b'>Some other contents </div>
</div>
Add div
</body>
</html>
This question is a duplicate :s
How can I implement prepend and append with regular JavaScript?
It's called prepending

Categories