Javascript,To add text to element which has a exsisting text-node - javascript

I want to add a text next to "Groceries" in the <h1> tag using either nodeValue property or textContentPropery. I have added two methods that are not working for me.Give me a reason why is it not happening not just the answer.
I don't want to use appendChild property in this.
<body>
<h1 id="head">Groceries</h1
><div id="li-container"
><ul
><li>item2</li
><li>item3</li
><li>item4</li
><li>item5</li
></ul
></div>
<script language="javascript" type="text/javascript">
var list = document.getElementsByTagName("li");
var head = document.getElementById("head").firstChild.nodeValue;
head.nodeValue = head + list.length;
//OR OR OR OR
//
var head = document.getElementById("head").firstChild.textContent;
head.textContent = head + list.length;
</script>
</body>

var head = document.getElementById("head").firstChild.nodeValue;
Here head contains only the text Groceries. So you can't access groceries.nodevalue
So you must use:
var head = document.getElementById("head").firstChild;
head.textContent = head.nodeValue + list.length;
Here, we're storing the reference of the textNode in head at first.
In second line, we are setting the textContent in that textNode.

In your case head is a string value as you are assigning the nodeValue of the header element to it, but any changes does to the variable value will not get reflected in the header as the string is not a mutable object.
You need to refer to the text node element and set its node value
var list = document.getElementsByTagName("li");
var head = document.getElementById("head").firstChild;
console.log(head)
head.nodeValue = head.nodeValue + list.length;
Demo: Fiddle

Related

JavaScript | appendChild to all classes

I have problem with append Child to whole classes in my document which the name of class is "onbackorder". Here is my code:
<script>
var first = document.createElement("p");
var text = document.createTextNode("On backorder");
first.appendChild(text);
var isRequestQuote = document.getElementsByClassName('onbackorder');
if (isRequestQuote.length > 0) {
document.querySelector(".onbackorder").appendChild(first);
}
</script>
For this moment function put selector randomly. How can I get same selector in whole document where class is "onbackorder".
Thank you
There are 2 points:
document.querySelector(".onbackorder") is just return first item. So you need to use document.querySelectorAll('.onbackorder').
The Document method querySelector() returns the first Element within
the document that matches the specified selector, or group of
selectors. If no matches are found, null is returned.
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
var first = document.createElement("p"); you have to create multiple reference variable to append to each onbackorder item. Because you cannot create only one and append to multiple items.
So I modified your code and make it works. You can check it at below:
var first = document.createElement("p");
var text = document.createTextNode("On backorder");
first.appendChild(text);
const allBackOrders = document.querySelectorAll('.onbackorder');
allBackOrders.forEach((item) => {
var newItem = first.cloneNode(true);
item.appendChild(newItem);
});
<div class="onbackorder"></div>
<div class="onbackorder"></div>
<div class="onbackorder"></div>

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.
}
});

Change existing DIV from a CLASS to an ID

Is this possible? Or is there a way to tack on and ID to an existing div?
This is my code. I can't get the code to work using classes, but I found when I used getElementById and changed the div to an ID, that it did. But I have a ton of already posted stuff so it would take forever to go through all those posts and change it manually to an ID.
Can I incorperate JQuery in this and still have it work? I tried that with something I stumbled across but it didn't work so I removed it. I don't remember what it is now though. :S
<div id="imdb" class="imdb">tt2382396</div>
<script>
function imdbdiv() {
var imdbmain = "http://www.imdb.com/title/";
var end = "/#overview-top";
var idnum = document.getElementsByClassName("imdb");
var newdiv = document.createElement("div");
var done = "<a href='" + imdbmain + idnum + end + "'>IMDB</a>";
newdiv.innerHTML = done;
document.body.appendChild(newdiv);
}
window.onload = imdbdiv();
</script>
Can anyone help. I cannot for the life of me figure this out.
JsFiddle
Your problem was, you were appending the collection returned by document.getElementsByClassName instead of looping through the elements in the collection. You can verify this by looking at the href property of the link in your jsFiddle. You must loop through the values, then access the data in their innerHTML property.
You can use document.querySelectorAll to get a list of all elements matching a certain CSS selector, in your case .imdb. This is more flexible, in case you want to select elements with more than one class. I've pasted the code from the updated jsFiddle below.
function imdbdiv() {
var imdbMain = "http://www.imdb.com/title/",
end = "/#overview-top",
imdbValueDivs = document.querySelectorAll('.imdb'),
length = imdbValueDivs.length,
// Iterator values
i,
newDiv,
newLink;
// Loop over all of your link value containers
for (i = 0; i < length; i++) {
// Create the container
newDiv = document.createElement('div');
// Create the new link
newLink = document.createElement('a');
newLink.href = imdbMain + imdbValueDivs[i].innerHTML + end;
newLink.innerHTML = "My favorite film";
// Add the link to the container,
// and add the container to the body
newDiv.appendChild(newLink);
document.body.appendChild(newDiv);
}
}
window.onload = imdbdiv();
If you have many such divs on your page, then it could be like this:
<div class="imdb">tt2382396</div>
<div class="imdb">tt2382396</div>
<div class="imdb">tt2382396</div>
<script>
function imdbdiv() {
var imdbmain = "http://www.imdb.com/title/";
var end = "/#overview-top";
var idnums = document.getElementsByClassName("imdb");
for (var i =0; i < idnums.length; i++) {
var newdiv = document.createElement("div");
var done = "<a href='" + imdbmain + idnums[i].innerText + end + "'>IMDB</a>";
newdiv.innerHTML = done;
document.body.appendChild(newdiv);
}
}
window.onload = imdbdiv();
</script>
See jsfiddle
UPDATE:
The following string was incorrect:
window.onload = imdbdiv;
Okay, so your question is a little bit unclear.
The way I understood your question is that you have a whole bunch of div elements with class attribute and what you want is to simply copy the class value to the id attribute of the div elements.
If that's correct then try something like this with jquery:
<script>
$(document).ready(function(){
$(".imdb").each(function(imdbDiv){
var classValue = imdbDiv.attr("class");
imdbDiv.attr("id", classValue);
});
});
</script>

Replace Text with Image - JavaScript (getElementsByClass)

I have a span:
<span class="attr attr-value">Brand Name</span>
And I want to replace that text with an image, based on the text
Here is what I have:
<script type="text/javascript">
var oldHTML = document.getElementsByClass('attr-value').innerHTML;
var filename = oldHTML.toLowerCase().replace(/ /g, '-').replace(/([^0-9a-z-])/g,'');
var newHTML = "<img src='http://www.example.com/" + filename + ".jpg'>";
document.getElementsByClass('attr-value').innerHTML = newHTML;
</script>
What am I doing wrong here?
This line is an issue:
var oldHTML = document.getElementsByClass('attr-value').innerHTML;
document.getElementsByClass should be document.getElementsByClassName, and it returns a NodeList, which doesn't have an innerHTML property. You'd want to loop through the NodeList to look at the innerHTML of each element.
Something like this (live example):
<script type="text/javascript">
(function() {
var list, index, element, filename;
list = document.getElementsByClassName('attr-value');
for (index = 0; index < list.length; ++index) {
element = list[index];
filename = element.innerHTML.toLowerCase().replace(/ /g, '-').replace(/([^0-9a-z-])/g,'');
element.innerHTML = "<img src='http://www.example.com/" + filename + ".jpg'>";
}
})();
</script>
Changes:
Put the whole thing in an anonymous function and immediately execute that function, to avoid creating global symbols.
Use the correct getElementsByClassName
Loop through them
Operate on the innerHTML of each element.
Notes:
IE doesn't have getElementsByClassName, so you'll want to be sure you're loading a script that provides it on IE. That's not provided in the live example above, use Firefox, Chrome, or Opera. (Just search for "getElementsByClassName for IE" and you'll find several implementations to choose from.)
The above script tag will need to be placed after all of the elements you want to process in the HTML file.
class="attr attr-value" and you're calling
document.getElementsByClass('attr-value').innerHTML
document.getElementsByClassName();
It should be, (e.g)
document.getElementsByClassName('attr-value')[0];

documentFragement

please take a look at the following code.
var oFra = document.createDocumentFragment();
var myDiv = document.createElement("div");
myDiv.id="myId";
oFra.appendChild(myDiv);
oFra.getElementById("myId");
In this case do i have ref to the div i just inserted inside documentFragement using the variable myDiv?
Lets say i move ahead and add this documentFragement to the actual DOM. Will I still be able to access the div with id="myId" using this "myDiv" variable???
If you try this, it works:
http://www.jsfiddle.net/dactivo/4BSaF/
The problem is that you cannot use "oFra" + getElementById directly, once you append the fragment, you can access the div "myId" in the DOM.
<div id="test"></div>
<script type="text/javascript">
var oFra = document.createDocumentFragment();
var myDiv = document.createElement("div");
myDiv.id="myId";
myDiv.innerHTML="hola";
oFra.appendChild(myDiv);
// oFra.getElementById("myId");
document.getElementById("test").appendChild(oFra);
alert(document.getElementById("myId").innerHTML);
</script>

Categories