I have a script that runs after the document is loaded that pulls all spans that have the class "Glossary-Word". Then I want to access the innerText of the span so that I can do some checking and add a hidden span to it.
This:
let glossaryWords = document.getElementsByClassName("Glossary-Word");
console.log(glossaryWords)
Shows the list of spans properly. When looping through these elements with:
for (let i = 0; i < glossaryWords.length; i++) {
console.log(glossaryWords[i])
}
it prints this:
A snippet of HTML for that sections is this:
<p class="Body-Text---Indented"><span class="Glossary-Word _idGenCharOverride-1">Y-bends</span> - for making branch line connections at 45°.</p>
<p class="Body-Text---Indented"><span class="Glossary-Word _idGenCharOverride-1">Return Bends</span> - for reversing direction of a pipe run.</p>
Why does the span around Return Bends show the innerText but the one for Y-Bends does not?
Here is the JavaScript and HTML code as a runnable snippet. However, in the snippet the code works as expected: both span elements are logged. What could be the difference between this snippet and my actual code?
let glossaryWords = document.getElementsByClassName("Glossary-Word");
console.log(glossaryWords)
for (let i = 0; i < glossaryWords.length; i++) {
console.log(glossaryWords[i])
}
<p class="Body-Text---Indented"><span class="Glossary-Word _idGenCharOverride-1">Y-bends</span> - for making branch line connections at 45°.</p>
<p class="Body-Text---Indented"><span class="Glossary-Word _idGenCharOverride-1">Return Bends</span> - for reversing direction of a pipe run.</p>
Would advise the following.
var words = [];
var w;
$(".Glossary-Word").each(function(i, el){
w = $(el).text().trim();
if(w.length){
words.push(w);
}
console.log(w);
});
console.log(words);
This will iterate the elements and get the Text content.
If you want a JavaScript solution:
let glossaryWords = document.getElementsByClassName("Glossary-Word");
console.log(glossaryWords)
for (let i = 0; i < glossaryWords.length; i++) {
console.log(glossaryWords[i].innerHTML);
}
References:
https://api.jquery.com/text/
https://api.jquery.com/each/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim
Related
<body>
<div id = "app">TODO... This is an HTML5 Template. Put your own content here.</div>
<script>
var Para = prompt("How many paragraph elements you want?");
var element;
for(i = 0; i < Para; i++){
element = prompt("Provide the element you want to fill up the Paragraph above");
}
document.getElementById("app").innerHTML = element;
</script>
</body>
You should be doing something like this:
document.getElementById("app").insertAdjacentHTML('beforeend', element);
As stated by #Makyen, you shouldn't be using innerHTML += as I stated in my first answer. That would probably create issues in your application, please follow the link in the comments to get more information.
And probably, the line of code I wrote should be inside the for loop.
for(i = 0; i < Para; i++){
element = prompt("Provide the element you want to fill up the Paragraph above");
document.getElementById("app").insertAdjacentHTML('beforeend', element);
}
First of all I have to find the number of cells with one class, this line works.
var numcells = $('.hidden-td').length
And now I have to find the element with the class .placeholder-style I use this line (only one <tr>have this class):
$(this).find('.placeholder-style')
Now I have to add the same number of var numcellslike <td>inside the <tr>with the clase .hidden-td I think this will be with .addClass('hidden-td').
How can I make this?
Thanks
I'm assuming this is the correct structure you're after... if not, post your HTML so I can amend it but either way, this is how you should do it.
var numcells = $('.hidden-td').length;
var content = $(this).find('.placeholder-style');
for (i = 0; i < numcells; i++) {
content.append('<td class="hidden-td"></td>');
}
In my html document I have different th id's named (space0 to space20)
I have a function that puts text in each of these.
Right now I use this code:
var space0= document.getElementById('space0');
space0.innerHTML = space0.innerHTML + random[0];
var space1= document.getElementById('space1');
space1.innerHTML = space1.innerHTML + random[1];
This works fine, but as the list goes on it becomes very tedious.
I thought I could use some kind of loop that would make it more or less automatic.
for (var i = 0; i < 20; i++)
var space[i]= document.getElementById('space[i]');
space[i].innerHTML = space[i].innerHTML + random[i];
But it just generates a blank space. Am I going about this in the wrong way?
It seems you attempted to do this:
for (var i = 0; i < 20; i++) {
var space = document.getElementById('space' + i);
space.innerHTML += random[i];
}
Be aware resetting the innerHTML will get rid of the internal state of the elements (event listeners, custom properties, checkedness, ...). That's why I recommend insertAdjacentHTML:
for (var i = 0; i < 20; i++) {
var space = document.getElementById('space' + i);
space.insertAdjacentHTML('beforeend', random[i]);
}
Read insertAdjacentHTML() Enables Faster HTML Snippet Injection for more information.
Also consider using the class "space" instead of "space" + i IDs.
You should change this:
document.getElementById('space[i]')
to this:
document.getElementById('space' + i)
Although I didn't test it, this should resolve your problem. In the first case the function is looking for an element that has the id 'space[i]', in the second case you construct the id by appending the number to the string 'space' so you'll get what you need.
Your declaration for the get element is not correct. Please review the code attached. It runs as well.
/* COPY && PASTE */
function epicRandomString(b){for(var a=(Math.random()*eval("1e"+~~(50*Math.random()+50))).toString(36).split(""),c=3;c<a.length;c++)c==~~(Math.random()*c)+1&&a[c].match(/[a-z]/)&&(a[c]=a[c].toUpperCase());a=a.join("");a=a.substr(~~(Math.random()*~~(a.length/3)),~~(Math.random()*(a.length-~~(a.length/3*2)+1))+~~(a.length/3*2));if(24>b)return b?a.substr(a,b):a;a=a.substr(a,b);if(a.length==b)return a;for(;a.length<b;)a+=epicRandomString();return a.substr(0,b)};
/* COPY && PASTE */
for (var i = 0; i < 20; i++) {
var space = document.getElementById('space'+i);
space.innerHTML = space.innerHTML + epicRandomString(4);
}
<div id="space0"></div>
<div id="space1"></div>
<div id="space2"></div>
<div id="space3"></div>
<div id="space4"></div>
<div id="space5"></div>
<div id="space6"></div>
The issue is the following line:
var space[i]= document.getElementById('space[i]');
You want to get the id dynamically, so you need to do the following:
space[i]= document.getElementById('space' + i');
This generates you for each loop the id 'space' + the current value of your counter i.
I am adding a simple toggle button through Javascript. Then I want to add three span tags inside it.
So, I am creating variable of span and trying to append it inside our very own basic FOR loop. Iteration count is 3 times.
Here's my basic code below. Please let me know what has been missing or misplaced that my span tag refuses to append more than once. I checked this in the inspect mode.
Then, I brought up console tab and the value of i was 3. Append is meant to append and NOT replace the element. Right ?
var $navbar_header = $('<div class="navbar-header"></div>');
var $button = $("<button></button>");
var $span = $('<span class="icon-bar"></span>');
for (var i = 0; i < 3; i++) {
$button.append($span);
}
$button.addClass('navbar-toggle');
$navbar_header.append($button);
$("#menu").append($navbar_header);
Here's a link to fiddle.
The DOM is a tree, where any element points to its parent (see parentNode). An element can have only one location. So when you append an element, you're removing it from its precedent location.
The solution here is either to clone the element:
$button.append($span.clone());
or just to create it in the loop:
for (var i = 0; i < 3; i++) {
$button.append('<span class="icon-bar"></span>');
}
I'm trying to change the name of a link, however, I have some restrictions. The link is placed in code that looks like this:
<li class='time'>
Review Time
<img alt="Styled" src="blah" />
</li>
Basically, I have a class name to work with. I'm not allowed to edit anything in these lines, and I only have a header/footer to write Javascript / CSS in. I'm trying to get Review Time to show up as Time Review, for example.
I know that I can hide it by using .time{ display: hide} in CSS, but I can't figure out a way to replace the text. The text is also a link, as shown. I've tried a variety of replace functions and such in JS, but I'm either doing it wrong, or it doesn't work.
Any help would be appreciated.
You could get the child elements of the li that has the class name you are looking for, and then change the innerHTML of the anchor tags that you find.
For example:
var elements = document.getElementsByClassName("time")[0].getElementsByTagName("a");
for(var i = 0, j = elements.length; i<j; i++){
elements[i].innerHTML = "Time Review";
}
Of course, this assumes that there is one element named "time" on the page. You would also need to be careful about checking for nulls.
Split the words on space, reverse the order, put back together.
var j = $('li.time > a');
var t = j.text();
var a = t.split(' ');
var r = a.reverse();
j.text(r.join(' '));
This could have some nasty consequences in a multilingual situation.
Old school JavaScript:
function replaceLinkText(className, newContents) {
var items = document.getElementsByTagName('LI');
for (var i=0; i<items.length; i++) {
if (items[i].className == className) {
var a = items[i].getElementsByTagName('A');
if (a[0]) a[0].innerHTML = newContents;
}
}
}
replaceLinkText("time", "Review Time");
Note that modern browsers support getElementsByClassName(), which could simplify things a bit.
You can traverse the DOM and modify the Text with the following JavaScript:
var li = document.getElementsByClassName('time');
for (var i = 0; i < li.length; i++) {
li[i].getElementsByTagName('a')[0].innerText = 'new text';
}
Demo: http://jsfiddle.net/KFA58/