Turn jQuery into vanilla JS - Insert p element after h1 - javascript

Any ideas on how I would convert this jQuery to vanilla JS:
$('.section > h1').after('<p>This paragraph was inserted with jQuery</p>');
I am new to jQuery and even newer to vanilla JS.
This is as far as I got:
var newP = document.createElement('p');
var pTxt = document.createTextNode('This paragraph was inserted with JavaScript');
var header = document.getElementsByTagName('h1');
Not sure where to go from here?

jQuery does a lot for you behind the scenes. The equivalent plain DOM code might look something like this:
// Get all header elements
var header = document.getElementsByTagName('h1'),
parent,
newP,
text;
// Loop through the elements
for (var i=0, m = header.length; i < m; i++) {
parent = header[i].parentNode;
// Check for "section" in the parent's classname
if (/(?:^|\s)section(?:\s|$)/i.test(parent.className)) {
newP = document.createElement("p");
text = document.createTextNode('This paragraph was inserted with JavaScript');
newP.appendChild(text);
// Insert the new P element after the header element in its parent node
parent.insertBefore(newP, header[i].nextSibling);
}
}
See it in action
Note that you can also use textContent/innerText instead of creating the text node. It's good that you're trying to learn how to directly manipulate the DOM rather than just letting jQuery do all the work. It's nice to understand this stuff, just remember that jQuery and other frameworks are there to lighten these loads for you :)

You might find this function useful (I didn't test)
function insertAfter(node, referenceNode) {
referenceNode.parentNode.insertBefore(node, referenceNode.nextSibling);
}

Oh it's not so bad...
var h1s = document.getElementsByTagName('h1');
for (var i=0, l=h1s.length; i<l; i++) {
var h1 = h1s[i], parent = h1.parentNode;
if (parent.className.match(/\bsection\b/i)) {
var p = document.createElement('p');
p.innerHTML = 'This paragraph was inserted with JavaScript';
parent.insertBefore(p, h1.nextSibling);
}
}

Related

JavaScript get textContent excluding children

First, I'm creating a library for JavaScript and I can not use jQuery. I'm trying to get the text content of an HTML element without the text contents of its children.
Both attributes innerText and textContent don't give me what needed, please help.
You can solve using DOM API as childNodes and nodeType.
var elChildNode = document.querySelector("#hello").childNodes;
var sChildTextSum = "";
elChildNode.forEach(function(value){
if(value.nodeType === Node.TEXT_NODE) {
console.log("Current textNode value is : ", value.nodeValue.trim());
sChildTextSum += value.nodeValue;
}
});
console.log("All text value of firstChild : ", sChildTextSum);
I created a sample code as above.
https://jsfiddle.net/nigayo/p7t9bdc3/
To get Author's Name from the following element, excluding <span>...:
<div class="details__instructor">
Author's Name<span ng-show="job_title">, Entrepreneur</span>
</div>
use childNodes[0]. For example:
document.querySelector('div.details__instructor').childNodes[0].textContent
Using only JavaScript (you specified you cannot use jQuery), and given that you have provided and know the id for the parent element:
document.getElementById('parent_element_id').childNodes[0].nodeValue;
You can also use .trim() to remove any trailing space characters left behind from the removal of any child element text:
document.getElementById('parent_element_id').childNodes[0].nodeValue.trim();
var mydiv = getElementByID("id");
function Get_text(element) {
var selected = element.cloneNode(true);
var text;
while (selected.firstChild) {
if (selected.firstChild.nodeType == 3) text = selected.firstChild.nodeValue;
selected.removeChild(selected.firstChild);
}
return text;
}
Get_text(mydiv);
I know many good solutions here exist, but none of them actually achieved what I needed (get the textContent of a single node, none of its children), so sharing this for future searchers.
var html = document.getElementsByTagName("*");
for (var i = 0; i < html.length; i++) {
var el = html[i];
for (var j = 0; j < el.children.length; j++) {
var child = el.children[j],
childTextContent = child.innerHTML;
// Remove all children tags, leaving only the actual text of the node.
childTextContent = childTextContent.replace(/\<.*\>.*\<\/.*\>/gmi, "");
// Also remove <img /> type tags.
childTextContent = childTextContent.replace(/\<.*\ \/\>/gmi, "");
console.log(childTextContent);
// Now you can do any type of text matching (regex) on the result.
}
});

chrome extension insert text issue

http://www.w3schools.com/js/js_statements.asp
i wrote a chrome extension to change the content of intro class but it is not working??
i have created a division and inserted it before intro class
the code is written in content.js
var div=document.createElement("div");
div.innerText='test123';
document.getElementsByClassName("intro").insertBefore(div,document.getElementsByClassName("intro")childNodes[0]);
getElementsByClassName returns a NodeList. As such, it has no such method as insertBefore.
If you want to insert your div inside all elements of class intro, you can accomplish this via a loop:
var elements = document.getElementsByClassName("intro");
for(var i = 0; i < elements.length; i++){
var div = document.createElement("div");
div.innerText = 'test123';
elements[i].insertBefore(div, elements[i].childNodes[0]);
}
Alternatively, if there is only one element, you can do:
var div = document.createElement("div");
div.innerText = 'test123';
document.getElementsByClassName("intro")[0].insertBefore(div, document.getElementsByClassName("intro")[0].childNodes[0]);

Regex to remove <script> and its content in Javascript

I am trying to remove scripts and their content from html body and this is what I have came up until now
just_text = just_text.replace(/<\s*script[^>]*>(<\s*\/script[^>]*>|$)/ig, '');
It does not work as want to, I still get the content.
Can you please help me?
Thank you
The answer to such questions is always the same: Don't use regular expressions. Instead, parse the HTML, modify the DOM and serialize it back to HTML if you need to.
Example:
var container = document.createElement('div');
container.innerHTML = just_text;
// find and remove `script` elements
var scripts = container.getElementsByTagName('script');
for (var i = scripts.length; i--; ) {
scripts[i].parentNode.removeChild(scripts[i]);
}
just_text = container.innerHTML;
If you want to remove the script tags from the page itself, it's basically the same:
var scripts = document.body.getElementsByTagName('script');
for (var i = scripts.length; i--; ) {
scripts[i].parentNode.removeChild(scripts[i]);
}

Append Ajax to an element using createDocumentFragment(); instead of create Element

This post was the most helpfull to understand createDocumentFragment() instead of createElement()
Should I use document.createDocumentFragment or document.createElement
I've understood that for performance reason using fragment will help on big dataset so i want to conver my function.
This is what i use right now and it works as desired => Get content from a php file with ajax and then append this content at the top of existing div#wrapperinside a new div.feedBox(r being the XMLHTTP /ACTIVE OBJECT)
r.onreadystatechange=function(){
if(r.readyState==4 && r.status==200){
//Want to convert this to createDocumentFrangment --START
var n = document.createElement("div");
n.className = "feedBox";
n.innerHTML = r.responseText;
document.getElementById("wrapper").insertBefore(n, document.getElementById("wrapper").firstChild);
//Want to convert this to createDocumentFrangment --END
}
}
This is what i tried, but what happens is the content is added but without the div.feedBox
var n = document.createElement("div");
n.className = "feedBox";
n.innerHTML = r.responseText;
var f = document.createDocumentFragment();
while (n.firstChild) { f.appendChild(n.firstChild); }
document.getElementById("wrapper").insertBefore(f, document.getElementById("wrapper").firstChild);
What did i miss? can you explain why and how to make it work?
Is this really a more efficient way of doing this?
PS: NO jquery please. I know it well and i use it widely on other project but i want this to be as small / lite / efficient as possible.
Shouldn't this line
while (n.firstChild) { f.appendChild(n.firstChild);
be
f.appendChild(n);
Also I see that you are not appending the div.feedBox to your DOM anywhere..
What happens if the while condition fails.. You are not appending anything to your DOM..
I am assuming this will work .. Not tested though
f.appendChild(n)
document.getElementById("wrapper").appendChild(f,
document.getElementById("wrapper").firstChild);
ALso better to use
.appendChild(f, instead of .insertBefore(f,
Check Fiddle
This is the full working function, any1 sould feel free to use it:
function ajax_fragment(php_file){
if (window.XMLHttpRequest){
r=new XMLHttpRequest();
} else{
r=new ActiveXObject("Microsoft.XMLHTTP");
}
r.onreadystatechange=function(){
if(r.readyState==4 && r.status==200){
var n = document.createElement("div"); //Create a div to hold the content
n.className = "feedBox"; //Give a class 'feddBox' to the div
n.innerHTML = r.responseText; //Put the response in the div
var f = document.createDocumentFragment(); //Create the fragment
f.appendChild(n); //Add the div to the fragment
//Append the fragment's content to the TOP of wrapper div.
document.getElementById("wrapper").insertBefore(f, document.getElementById("wrapper").firstChild);
}
}
r.open("GET",php_file,true);
r.send();
}

How can I make text bold with nodes and .createElement("b")?

I have to make text bold if I click on a button using nodes and createElement but I don't really know how...
html (This is the text I want to make bold):
<p id="textalt">Dies ist ein Text in einem P-Tag</p>
javascript:
function fettmachen(){
var neuB = document.createElement("b");
document.getElementById("textneu").insertBefore(neuB, document.getElementById("textneu").nextSibling);
}
I don't know how it works.
"I have to do it with nodes and createElement"
function fettmachen(){
// create the "b" element
var neuB = document.createElement("b");
// fetch the "textneu" element by ID
var textneu = document.getElementById("textneu");
// append the firstChild of "nextneu" to the "neuB"
neuB.appendChild(textneu.firstChild);
// append the "neuB" to the "nextneu"
nextneu.appendChild(neuB);
}
I suggest, instead of adding new tags, just use CSS, and add a class to the element.
CSS:
.boldText{
font-weight: bold;
}
JavaScript:
function fettmachen(){
document.getElementById("textalt").className += ' boldText';
}
I'd just put a style on the <p> tag on the button press. Maybe something like...
function fettmachen(){
var neuB = document.getElementById("textalt");
neuB.style.fontWeight = "bold";
}
Well, you could use the following code. It's longer and could be condensed - I find it clearer to read, personally.
function fettmachen()
{
var pElem = document.getElementById('textAlt');
var text = pElem.innerHTML;
var bElem = document.createElement('b');
bElem.innerHTML = text;
pElem.innerHTML = '';
pElem.appendChild(bElem);
}
This is how you make the text bold
function fettmachen(){
var p = document.getElementById("textneu");
p.style.fontWeight = "bold;"
}
If you have to use js for some reason for instance you need to only bold certain words maybe, and don't have access to the style sheet here you go. Otherwise use what Rocket has suggested.
Seriously only use a solution like this if at some point you will need to only bold certain words, or groups of words within an element.
function fettmachen(){
var neuB = document.createElement("b"),
textEl = document.getElementById("textalt"),
text = textEl.textContent;
neuB.textContent = text;
textEl.textContent = "";
textEl.appendChild(neuB);
}
Live Demo
And to unbold.
function unbold(){
var textEl = document.getElementById("textalt"),
boldEls = textEl.getElementsByTagName("b"),
text = "";
for(var i = 0; i < boldEls.length; i++){
text+=boldEls[i].textContent;
textEl.removeChild(boldEls[i]);
}
textEl.textContent = text;
}
Live Demo 2

Categories