Adding text to an existing text element in JavaScript via DOM - javascript

I am trying to figure how to add text to a p tag or h1 tag that already has a text node.
For example:
var t = document.getElementById("p").textContent;
var y = document.createTextNode("This just got added");
t.appendChild(y);
<p id="p">This is some text</p>
This code gives an error appendChild is not a function. Most of the help pages first create a p tag and then append the text.
What is the right way to add text to an existing text element?
PS: I've used innerHTML before to do this, but for learning purposes I want to avoid it here.

The reason that appendChild is not a function is because you're executing it on the textContent of your p element.
You instead just need to select the paragraph itself, and then append your new text node to that:
var paragraph = document.getElementById("p");
var text = document.createTextNode("This just got added");
paragraph.appendChild(text);
<p id="p">This is some text</p>
However instead, if you like, you can just modify the text itself (rather than adding a new node):
var paragraph = document.getElementById("p");
paragraph.textContent += "This just got added";
<p id="p">This is some text</p>

Instead of appending element you can just do.
document.getElementById("p").textContent += " this has just been added";
document.getElementById("p").textContent += " this has just been added";
<p id ="p">This is some text</p>

The method .appendChild() is used to add a new element NOT add text to an existing element.
Example:
var p = document.createElement("p");
document.body.appendChild(p);
Reference: Mozilla Developer Network
The standard approach for this is using .innerHTML(). But if you want a alternate solution you could try using element.textContent.
Example:
document.getElementById("foo").textContent = "This is som text";
Reference: Mozilla Developer Network
How ever this is only supported in IE 9+

What about this.
var p = document.getElementById("p")
p.innerText = p.innerText+" And this is addon."
<p id ="p">This is some text</p>

remove .textContent from var t = document.getElementById("p").textContent;
var t = document.getElementById("p");
var y = document.createTextNode("This just got added");
t.appendChild(y);
<p id ="p">This is some text</p>

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").append(" <b>Appended text</b>.");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button id="btn1">Append text</button>
</body>
</html>

var t = document.getElementById("p").textContent;
var y = document.createTextNode("This just got added");
t.appendChild(y);
<p id="p">This is some text</p>

Related

How to wrap html text into spans with javascript

I want to wrap a text from html in a span so it should be like this
<p>Test yes</p>
into
<p><span>Test</span></p>
with javascript dom. Can anybody help me with this?
Try this.
document.getElementsByTagName("p")[0].innerHTML = '<span>' + document.getElementsByTagName("p")[0].innerHTML + '</span>';
<p>Test</p>
document.querySelectorAll("p").forEach(element => {
element.innerHTML = '<span>' + element.innerHTML + '</span>';
});
<p>Test1</p>
<p>Test2</p>
<p>Test3</p>
<p>Test4</p>
Not just text, in case you have some other html entities as well, inside the element like p tag here, here is what you can do :
var parent = document.querySelector("p");
parent.innerHTML = "<span>" + parent.innerHTML + "</span>"
Check out this snippet:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<p id="test_para">Test yes</p>
<script type="text/javascript">
var p = document.getElementById('test_para')
var span = document.createElement('span');
var node = document.createTextNode(p.innerHTML);
span.appendChild(node);
p.innerHTML = '';
p.appendChild(span);
</script>
</body>
</html>
In the snippet we did following things:
First we assigned id test_para to our paragraph. Through this id we locate it and store in variable p.
Second we create span element using createElement() method.
Third we create a text node using createTextNode() method and store text of our paragraph inside it.
Next we set add this node to span element we just created using appendChild() method.
Finally we make our paragraph empty and append newly created span element to it using appendChild() method.
There is another more less sophisticated way to do this:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<p id="test_para">Test yes</p>
<script type="text/javascript">
var p = document.getElementById('test_para')
p.innerHTML = '<span>'+p.innerHTML+'</spn>';
</script>
</body>
</html>
Here we locating our paragraph using id as we did in the snippet above. But rather than creating HTML elements using JavaScript, we just changing the HTML inside of our paragraph using its innerHTML property.
This, one line would do!
document.querySelectorAll("p").forEach(e => e.innerHTML = `<span>${e.innerHTML}</span>`)

removing tag name but keep tag

Hello I have a <strong></strong> Tag nested in a paragraph <p></p>, I'm trying to remove the <strong> tag but keep the text or the value. Something similar to unwrapping in jquery but in javascript.
I tried this code on a dummy HTML page and it works fine
<html>
<body>
<p>aaa <Strong>bbbbb</Strong></p>
<p>acccaa <Strong>ddddd</Strong></p>
<p>eeee <Strong>ffff</Strong></p>
<script>
var p = document.getElementsByTagName("p");
for(var i=0;i<p.length;i++){
var strongs = p[i].getElementsByTagName("strong");
for(var j=0;j<strongs.length;j++){
p[i].replaceChild(document.createTextNode(strongs[j].innerText),strongs[j]);
}
}
</script>
</body>
</html>
But as soon as I try the same code on a real page example: https://www.bustle.com/privacy
I get this error:
Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node.
Any idea on how to get this to work on the example or any other example?
getElementsByTagName() returns a live NodeList. So when you replace a tag, the indexes of all the following elements shift down and the code fails when you have more than one <strong> tag in the same paragraph. As a result, it will skip some tags.
The solution is to convert the NodeList to an array so it doesn't change while you're looping.
Another problem in your real page that isn't in the snippet is that the <strong> tags can be nested deeply within the <p>. You should use strongs[j].parentElement to get its direct parent, rather than assuming that the p[i] is the parent.
var p = document.getElementsByTagName("p");
for (var i = 0; i < p.length; i++) {
var strongs = Array.from(p[i].getElementsByTagName("strong"));
for (var j = 0; j < strongs.length; j++) {
strongs[j].parentElement.replaceChild(document.createTextNode(strongs[j].innerText), strongs[j]);
}
}
<html>
<body>
<p>aaa
<Strong>bbbbb</Strong> - <strong>12345</strong></p>
<p>acccaa <span><Strong>ddddd</Strong> x</span></p>
<p>eeee
<Strong>ffff</Strong>
</p>
</body>
</html>
You can also avoid the nested loops by using a query selector.
var strongs = document.querySelectorAll("p strong");
strongs.forEach(strong => strong.parentElement.replaceChild(document.createTextNode(strong.innerText), strong));
<html>
<body>
<p>aaa
<Strong>bbbbb</Strong> - <strong>12345</strong></p>
<p>acccaa <span><Strong>ddddd</Strong> x</span></p>
<p>eeee
<Strong>ffff</Strong>
</p>
</body>
</html>
No need to loop through paragraphs to remove <strong>. Simply removing all 'strongs' in place works fine.
function removeStrongs() {
let strongs = document.querySelectorAll('strong');
strongs.forEach(strong => {
strong.insertAdjacentText('afterend', strong.innerText);
strong.remove();
});
}
<h4>This is a <strong>Title</strong></h4>
<p>
Now is the time for all <strong>good</strong> men to come to the <strong>aid</strong> of the party.
</p>
<p>A <strong>quick brown</strong> fox jumps over the lazy dog.</p>
<button onclick="removeStrongs();">Remove Strongs</button>

replace with some other text

I'm stuck in a thing where I need to replace with some other text.
I have tried the following code.
var text = $("#nbspData").text().replace(' ','a');
$("#removedData").html(text);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="nbspData">this is me.</p>
<p id="removedData"></p>
But when I inspect the code the is not removed.
That happens because text() doesn't returns those encoded chars, it just returns the text you're seeing, e.g.: "this is me". So there is nothing to replace. Change text() to html():
var text = $("#nbspData").html().replace(' ','a');
var text = $("#nbspData").html().replace(' ','a');
$("#removedData").html(text);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="nbspData">this is me.</p>
<p id="removedData"></p>
Additional info: Use a regex replace if you want to replace all occurences of :
var text = $("#nbspData").html().replace(/\ /g,'a');
console.log(text);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="nbspData">this is me.</p>
This is a solution for HTML tag and &nbsp etc and you can remove and add conditions
based on your reuirement
convertHtmlToText(passHtmlBlock)
{
str = str.toString();
return str.replace(/<[^>]*(>|$)| |‌|»|«|>/g, 'replaceWithAnyText');
}

Javascript help on dynamically creating html elements and populating the element onto the DOM

So in the script tag here I have an array myArr that is printed into p tag in the html:
<html>
<body>
<h1>Header 1</h1>
<div>
<p id="test"></p>
</div>
</body>
</html>
<script>
var myArr = ["abc", 123, "test"];
document.getElementById('test').innerHTML = myArr;
</script>
All that works and is good. So, I have a couple of questions about this, as I'm pretty new to javascript.
I know how to iterate through the array and print out each element within the script tag. But how would I be able to display it into the html? Is there a way to dynamically create the p tags with the element from the array as the contents?
And would I be able to easily add stying into the dynamically created p tag?
Can this kind of thing be done using something like jquery? or another popular simple javascript library?Unfortunately, I will be unable to run a full fledged javascript framework. I am only able to run a basic library.
I attempted a try here:
var my_arr = ["test", "abc", 123];
var arr_length = my_arr.length;
for (i = 0; i < arr_length; i++) {
document.createElement("p");
document.getElementById('test').innerHTML = arr_length;
my_arr[i]
}
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<div id="test">
</div>
You just need to forEach over the array. Inside the callback, create a p, append it to the desired container, and set its textContent to the array element. No frameworks/libraries required:
const test = document.getElementById('test');
const my_arr = ["test", "abc", 123];
my_arr.forEach((item) => {
test.appendChild(document.createElement('p'))
.textContent = item;
});
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<div id="test">
</div>
Array methods are generally preferrable to for loops, but if you really wanted to use a for loop like in your original code, you would have to set the textContent of the created p to my_arr[i], in addition to appending the p to test:
var my_arr = ["test", "abc", 123];
var arr_length = my_arr.length;
const test = document.getElementById('test');
for (i = 0; i < arr_length; i++) {
const p = document.createElement("p");
p.textContent = my_arr[i];
test.appendChild(p);
}
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<div id="test">
</div>

Referencing elements by 'class' and not 'id'

I am trying to reference elements (to get pieces of text) in a news website and display them in a simple way.
I watched a YouTube tutorial about referencing elements and it referenced paragraphs using 'getElementById.'
The website I want to use doesn't use 'Id=' very much, it mostly uses 'class=' so I cannot use this same method.
I tried swapping the above 'getElementById' for 'getElementsByClassName' however I am getting the answer 'undefined.'
Code:
<html lang="en">
<body>
<p class="para1" > this is the 1st paragraph </p>
<p> <br/> </p>
<p> <br/> </p>
<p> <br/> </p>
<p class="para2" > this is the 2nd paragraph </p>
</body>
</html>
<script type="text/javascript">
var input=document.createElement("input");
input.type="button";
input.value="Check";
input.onclick = showAlert1;
input.setAttribute("style", "font-size:18px;position:absolute;top:100px;right:40px;");
document.body.appendChild(input);//Placement of check button on website;
function showAlert1()
{
alert(document.getElementsByClassName('para2').innerHTML);
}
</script>
getElementsByClassName returns a collection of elements(like an array). So you need to access those using indexes like this:
document.getElementsByClassName("someClass")[0];
//Or if you want to access all
var len = document.getElementsByClassName("someClass").length;
for(var i=0;i<len;i++){
//access like document.getElementsByClassName("someClass")[i]
}
In your case
document.getElementsByClassName('para2')[0].innerHTML
you have to add the script after html tag.
<div class="increased">hi</div> <!-- first specify the tag-->
<script type="text/javascript"> <!-- then call in script-->
var i = 23;
var elems=document.getElementsByClassName("increased");
for(var k = 0; k < elems.length; k++) {
elems[k].style.size = '100px';
}
</script>

Categories

Resources