I'm trying to create a new div in Javascript with two spans in it, each containing a string of text. They are then meant to be inserted before div.two in div.inner.
The div I'm trying to insert it into only has a class and I cannot target it by any ID, unfortunately.
I have also created a codepen here: https://codepen.io/lisaschumann/pen/BXqJKY
Any help is massively appreciated!
HTML
<html>
<div class="inner">
<div class="one"></div>
<div class="two"></div>
</div>
</html>
JS
window.onload=function(){
var infobox = document.createElement("div");
infobox.classList.add('infobox');
var spanOne = document.createElement("div");
var spanOneText = document.createTextNode('Important text 1');
var spanTwo = document.createElement("div");
var spanTwoText = document.createTextNode('Important text 2');
spanOne.appendChild(spanOneText);
spanTwo.appendChild(spanTwoText);
infobox.appendChild(spanOne);
infobox.appendChild(spanTwo);
var targetDiv = document.getElementsByClassName("inner");
targetDiv.insertBefore(infobox, targetDiv.childNodes[1]);
}
Errors:
Cannot read property '1' of undefined
at window.onload
The main issue is that getElementsByClassName returns a live collection of nodes rather than one node and so you would need to access the correct node in that list similar to an array: targetDiv[0], perhaps.
The easier method is to use querySelector to grab the element you want using its class, for example:
var parent = document.querySelector(".inner");
var two = document.querySelector(".two");
parent.insertBefore(infobox, two);
But! there's even a shortcut method you can use here that allows you to add an HTML string direct to the DOM which might save you a bit of time, and some code.
// Create the HTML
const html = `
<div>
<span>Text alpha</span>
<span>Text beta</span>
</div>`;
// Grab the element containing your "two" class
const two = document.querySelector('.inner .two');
// Using insertAdjacentHTML to add the HTML before the two element
two.insertAdjacentHTML('beforebegin', html);
<div class="inner">Inner
<div class="one">one</div>
<div class="two">two</div>
</div>
insertAdjacentHTML
This doesn't work because of these lines
var targetDiv = document.getElementsByClassName("inner");
targetDiv.insertBefore(infobox, targetDiv.childNodes[1]);
document.getElementsByClassName returns a NodeList. targetDiv.childNodes is undefined, because childNodes doesn't exist on a NodeList.
You need to either use a list operation like Array.prototype.forEach, change getElementsByClassName to getElementByClassName (note the s) or access the first node in the node list using the array indexer syntax.
I assume you meant to do something like this:
var targetDiv = document.getElementByClassName('inner')
targetDiv.insertBefore(infobox, targetDiv.childNodes[1])
This will insert a node in between the first and second child of the first DOM node with the class inner.
Try this out , targetDiv is an array by default due to the getElementsByClassName method , even though it has a single element.Hence you need to specify the index i.e. 0 ( as it's the first element of the array)
var targetDiv = document.getElementsByClassName("inner")[0]; targetDiv.insertBefore(infobox, targetDiv.children[1]); }
Using JQuery
$(document).ready(function(){
$(`<div>Important text 1<span></span>Important text 2<span></span></div>`).insertBefore( ".inner .two" );
)
I would encourage you to use JQuery and then shift to vanilla javascript later on. You can do simple tasks like this in just few lines of code and it is also easily debuggable because of that
Related
I have a website built in Expression Engine. In the back-end there is a code snippet that takes care of a JavaScript request and build a page based on the request.
I have a HTML Page without head tag.
This page is without styling
Sample:
<div class="top-arrow"><p><!--- Rest of code --></p>
</div>
<!-- Html page continues-->
I have added the following code in my attempt and it doesnt seem to work.
var span = document.createElement("span"); //Test element
span.textContent = "A <span> element.";
var node = document.getElementsByClassName("top-arrow");
node.insertBefore(span);
Below is what I get:
TypeError: node.insertBefore is not a function
node.insertBefore(span);
How best can I append text before the div with plain JavaScript.
getElementsByClassName will return array-like node-list which does not have method insertBefore
The Node.insertBefore(newNode, referenceNode) method inserts the specified node before the reference node as a child of the current node(If referenceNode is null, the newNode is inserted at the end of the list of child nodes)
Note: referenceNode is not an optional argument, if there is no ant ref node, pass null
Try this:
var span = document.createElement("span");
span.textContent = "A <span> element.";
var node = document.getElementsByClassName("top-arrow")[0];
//_____________________________________________________^^(Get the first element from collection)
node.insertBefore(span, null);
<div class="top-arrow">
<p>
</p>
</div>
document.getElementsByClassName("top-arrow") will return a live HTMLCollection. You can use it like an array:
node = document.getElementsByClassName("top-arrow")[0];
Also, if you want the new node to appear before top-arrow you need to do:
node.parentNode.insertBefore(span, node);
As it is node has no children, so there is no need to do insertBefore.
Even though your HTML code has no body and head, the browser will 'fix' your HTML and add one.
I would write your code like this:
var span = document.createElement("span"); //Test element
span.appendChild(document.createTextNode("A <span> element."));
var node = document.getElementsByClassName("top-arrow")[0];
node.parentNode.insertBefore(span, node);
Function getElementsByClassName() returns an array containing nodes with class specified. If you want to insertBefore or append anything to it you need to specify index of an element in this array. Also, insertBefore requires two arguments in function call (elementToInsert, elemenBeforeWhichYouWantToInsert). So, something like this should work:
document.getElementsByClassName('top-arrow')[0].insertBefore(element, beforeWhatToInsert);
Thank you guys for all your input they are very informative. I have solved this without the need of manipulating my DOM element by simply copying the dynamic part of the page and actually creating a new template in the back-end of Expression Engine and my problem was solved.
Working on a personal project that parses through an HTML document inserted into a textarea and produces a new HTML document with added modifications.
What my issue is, I want split certain divs with class="dog" into an array with each element in the array being divs of class of dog.
HTML:
<div class="dog">
<div class="mouth"></div>
<dig class="legs"></dig>
</div>
<div class="dog">
<div class="mouth"></div>
<dig class="legs"></dig>
</div>
JS Idea:
dogs[x] = intext.slice(intext.indexOf('<div class="dog"'), /*next instance of dog*/);
Array would look like:
dog[0] = <div class="dog">
<div class="mouth"></div>
<dig class="legs"></dig>
</div>
I tried using .indexOf('<div class="dog"') to try and create an array of indexes so I can use it to split the main string but no luck.
Any ideas of how I can accomplish this?
There exists a feature called query selectors. With these you can select all elements with a certain class, or all elements of a certain tag, ...
This will suit your specific need: querySelectorAll
the regular querySelector() will only select the first element which is why you need to use querySelectorAll(). It will give you a list of elements with which you can continue working.
Example:
var dogDivs = document.querySelectorAll(".dog");
EDIT:
As you have just now mentioned it is text from a textarea, as suggested by an other answer you could first load it into your DOM structure. Preferrably in a hidden element so that the user is unaware of it.
First you need to load the content onto the DOM:
document.createElement("div").innerHtml(intext);
Then you can find the dog elements as the other answers have suggested:
var elements = document.getElementsByClassName('dog');
Be careful when loading user inputted data into the DOM, this can open doors to being hacked.
You should never parse html as a string. Use a DOMParser to convert it to a document and then you can use all the standard methods
var parser = new DOMParser();
var doc = parser.parseFromString(stringContainingHTMLSource, "Text Area Content");
divs = doc.getElementsBYTagName("div");
Then you can use the built in Document interface. For your specific case, here are a few methods you can use.
get an array of all divs:
document.getElementsByTagName("div");
get an array of all divs with a specific class:
document.getElementsByClassName("dog");
get an array of all divs with a specific id:
document.getElementById("id");
The full list of very useful methods can be found on MDN.
var elements = document.getElementsByClassName('dog');
var arr = [].slice.call(elements);
arr is the array you want to have. elements is HTMLCollection, and doesn't have array prototype methods.
You can try getting all elements with class dog:
var dogs = document.getElementsByClassName("dog");
But this will return all elements with class dog. Then you can try this snippet:
function splitByClass(tag, cl) {
var els = document.getElementsByClassName(cl);
var res = [];
for (i = 0; i < els.length; i++) {
if (els[i].tagName.toLowerCase() == tag.toLowerCase()) {
res.push(els[i]);
}
}
return res;
}
console.log(splitByClass("div","dog"));
If you want to parse it as text without converting it into a DOM object which could potentially error if there is any mistakes with the users input formatting. Try a solution like the one I suggested here for searching XML code:
https://stackoverflow.com/a/34299948/1011603
This will let you search for a start tag, eg and an end tag, you just need to tweak the .substring sizing for the size of your search start/end tag eg the div.
For the thing you are doing you don't use the slice tool. This would be used for a String and you don't use the index of because that's just searching a string for a specific part.
What you do want to use is the
document.querySelectorAll(".example");
You will put the class dog where the .example is as the same format.
This command will return an array of all of the possible divs
If you need any more help, go to this link
http://www.w3schools.com/jsref/met_document_queryselectorall.asp
what's the different between using:
// assuming using elements/tags 'span' creates an array and want to access its first node
1) var arrayAccess = document.getElementsByTagName('elementName')[0]; // also tried property items()
vs
// assuming I assign an id value to the first span element/tag
// specifically calling a node by using it's id value
2) var idAccess = document.getElementById('idValue');
then if I want to change the text node....when using example 1) it will not work, for example:
arrayAccess.firstChild.nodeValue = 'some text';
or
arrayAccess.innerText/innerHTML/textContent = 'some text';
If I "access" the node through its id value then it seems to work fine....
Why is it that when using array it does not work? I'm new to javascript and the book I'm reading does not provide an answer.
Both are working,
In your first case you need to pass the tag name instead of the element name. Then only it will work.
There might be a case that you trying to set input/form elements using innerHTML. At that moment you need to use .value instead of innerHTML.
InnerHTML should be used for div, span, td and similar elements.
So your html markup example:
<div class="test">test</div>
<div class="test">test1</div>
<span id="test">test2</span>
<button id="abc" onclick="renderEle();">Change Text</button>
Your JS code:
function renderEle() {
var arrayAccess = document.getElementsByTagName('div')[0];
arrayAccess.innerHTML = "changed Text";
var idEle = document.getElementById('test');
idEle.innerHTML = "changed this one as well";
}
Working Fiddle
When you use document.getElementsByTagName('p'), the browser traverses the rendered DOM tree and returns a node list (array) of all elements that have the matching tag.
When you use document.getElementById('something'), the browser traverses the rendered DOM tree and returns a single node matching the ID if it exists (since html ID's are unique).
There are many differences when to use which, but one main factor will be speed (getElementById is much faster since you're only searching for 1 item).
To address your other question, you already have specified that you want the first element in the returned nodeList (index [0]) in your function call:
var arrayAccess = document.getElementsByTagName('elementName')[0];
Therefore, arrayAccess is already set to the first element in the returned query. You should be able to access the text by the following. The same code should work if you used document.getElementById to get the DOM element:
console.log(arrayAccess.textContent);
Here's a fiddle with an example:
http://jsfiddle.net/qoe30w2w/
Hope this helps!
I've searched around using Google and Stack Overflow, but I haven't seemed to find a answer to this. I want to write text inside a <div> element, using JavaScript, and later clear the <div> element, and write more text into it. I am making a simple text adventure game.
This is what I am trying to do:
<DOCTYPE!HTML>
<body>
<div class="gamebox">
<!-- I want to write in this div element -->
</div>
</body>
As a new user to JavaScript, how would I be able to write inside the div element gamebox? Unfortunately, my JavaScript skills are not very good, and it would be nice if you can patiently explain what happens in the code.
You can use querySelector to get a reference to the first element matching any CSS selector. In your case, a class selector:
var div = document.querySelector(".gamebox");
querySelector works on all modern browsers, including IE8. It returns null if it didn't find any matching element. You can also get a list of all matching elements using querySelectorAll:
var list = document.querySelectorAll(".gamebox");
Then you access the elements in that list using 0-based indexes (list[0], list[1], etc.); the length of the list is available from list.length.
Then you can either assign HTML strings to innerHTML:
div.innerHTML = "This is the text, <strong>markup</strong> works too.";
...or you can use createElement or createTextNode and appendChild / insertBefore:
var child = document.createTextNode("I'm text for the div");
div.appendChild(span); // Put the text node in the div
Those functions are found in the DOM. A lot of them are now covered in the HTML5 specification as well (particularly Section 3).
Select a single element with document.querySelector or a collection with document.querySelectorAll.
And then it depends, on what you want to do:
Writing Text into the div or create an Element and append it to the div.
Like mentioned getElementsByClassName is faster. Important to know it when you use this you get returned an array with elements to reach the elment you want you specify its index line [0], [1]
var gameBox = document.getElementsByClassName('gamebox')[0];
Here how you can do it
//returns array with elements
var gameBox = document.getElementsByClassName('gamebox');
//inner HTML (overwrites fsd) this can be used if you direcly want to write in the div
gameBox[0].innerHTML ='<p>the new test</p>';
//Appending when you want to add extra content
//create new element <p>
var newP = document.createElement('p');
//create a new TextNode
var newText = document.createTextNode("i'm a new text");
//append textNode to the new element
newP.appendChild(newText);
//append to the DOM
gameBox[0].appendChild(newP);
https://developer.mozilla.org/en-US/docs/Web/API/document.createElement
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName
For instance in the snippet below - how do I access the h1 element knowing the ID of parent element (header-inner div)?
<div id='header-inner'>
<div class='titlewrapper'>
<h1 class='title'>
Some text I want to change
</h1>
</div>
</div>
Thanks!
function findFirstDescendant(parent, tagname)
{
parent = document.getElementById(parent);
var descendants = parent.getElementsByTagName(tagname);
if ( descendants.length )
return descendants[0];
return null;
}
var header = findFirstDescendant("header-inner", "h1");
Finds the element with the given ID, queries for descendants with a given tag name, returns the first one. You could also loop on descendants to filter by other criteria; if you start heading in that direction, i recommend you check out a pre-built library such as jQuery (will save you a good deal of time writing this stuff, it gets somewhat tricky).
If you were to use jQuery as mentioned by some posters, you can get access to the element very easily like so (though technically this would return a collection of matching elements if there were more than one H1 descendant):
var element = $('#header-inner h1');
Using a library like JQuery makes things like this trivial compared to the normal ways as mentioned in other posts. Then once you have a reference to it in a jQuery object, you have even more functions available to easily manipulate its content and appearance.
If you are sure that there is only one H1 element in your div:
var parent = document.getElementById('header-inner');
var element = parent.GetElementsByTagName('h1')[0];
Going through descendants,as Shog9 showed, is a good way too.
It's been a few years since this question was asked and answered. In modern DOM, you could use querySelector:
document.querySelector('#header-inner h1').textContent = 'Different text';
<div id='header-inner'>
<div class='titlewrapper'>
<h1 class='title'>
Some text I want to change
</h1>
</div>
</div>
The simplest way of doing it with your current markup is:
document.getElementById('header-inner').getElementsByTagName('h1')[0].innerHTML = 'new text';
This assumes your H1 tag is always the first one within the 'header-inner' element.
To get the children nodes, use obj.childNodes, that returns a collection object.
To get the first child, use list[0], that returns a node.
So the complete code should be:
var div = document.getElementById('header-inner');
var divTitleWrapper = div.childNodes[0];
var h1 = divTitleWrapper.childNodes[0];
If you want to iterate over all the children, comparing if they are of class “title”, you can iterate using a for loop and the className attribute.
The code should be:
var h1 = null;
var nodeList = divTitleWrapper.childNodes;
for (i =0;i < nodeList.length;i++){
var node = nodeList[i];
if(node.className == 'title' && node.tagName == 'H1'){
h1 = node;
}
}
Here I get the H1 elements value in a div where the H1 element which has CSS class="myheader":
var nodes = document.getElementById("mydiv")
.getElementsByTagName("H1");
for(i=0;i<nodes.length;i++)
{
if(nodes.item(i).getAttribute("class") == "myheader")
alert(nodes.item(i).innerHTML);
}
Here is the markup:
<div id="mydiv">
<h1 class="myheader">Hello</h1>
</div>
I would also recommend to use jQuery if you need a heavy parsing for your DOM.