I don't understand why my extraInfo variable isn't being printed out onto the webpage.
The information is being retrieved correctly (I've tested this with alert()) but I just cannot figure out why it isn't replacing the span text with the returned value.
I've tried sending it out wrapped in P tags too and although no errors come out, it still doesn't amend the text.
https://github.com/ralam87/Quote-generator
Where am I going wrong?
document.getElementById("source").getElementsByClassName("citation")[0] = extraInfo;
I gone through your example.
Note: when you are trying to assign the citation to first element with .citation class that time the there are no elements present with the class citation because it get replaced when you set the value to source element just before citation document.getElementById("source").innerHTML = author;.
This are possible solution
change this document.getElementById("source").getElementsByClassName("citation")[0] = extraInfo; to document.getElementsByClassName("citation")[0].innerHtml = extraInfo;
remove the id from <p id="source">
create another <span> or <div> or <p> element inside the existing <p> and assign the id=source to that inner element. for example <p><span id="source"></span><span id="citation"></span></p>.
If you want to have the , after the source name then at the time of assigning the document.getElementById("source").innerHTML = author + ',';.
If you allow me i can also contribute this directly to you git
repository.
Related
i need inside my CKEditor some boilerplate verbiage that is not editable, then the rest of the my string information. I concatenate the boilerplate verbiage [which is in a p tag], to a string variable that my CKEditor displays inside a certain div. By the time the verbiage, here:
<p id='abc' contentEditable='false'>verbiage</p>
... and the string information is displayed on the page, they are deep inside a number of nested tags - within a body with multiple classes. So both the verbiage, which is now in only a p tag with no attributes[they got stripped out], is nested way inside the original body tag [the first body tag, way up in the page] with lots and lots of divs, then finally comes an iframe, then ... the verbiage and string are like this:
<body contenteditable="true" class="cke_editable cke_editable_themed cke_contents_ltr cke_show_borders" spellcheck="false">
<p>boilerplate verbiage</p>
...then the rest of the information is displayed in the editor, inside various spans, etc. i need to make the boilerplate verbiage readonly, contentEditable='false'. Yet everything I try both from the console in Chrome, and in code.... nothing changes that boilerplate verbiage tag. i have tried various things, including these - perhaps you can see where I need to tweak something; and i hope this will show you things i have tried and that i am run out of options so far:
jQuery("body.cke_editable.cke_editable_themed.cke_contents_ltr.cke_show_borders").first().contentEditable='false';
jQuery("body.cke_editable.cke_editable_themed.cke_contents_ltr.cke_show_borders").attr("readonly", "1");
jQuery("body.cke_editable.cke_editable_themed.cke_contents_ltr.cke_show_borders p:first-child").contentEditable='false';
jQuery("body.cke_editable.cke_editable_themed.cke_contents_ltr.cke_show_borders").find( "p" ).contentEditable='false';
jQuery("iframe", ".cke_editable.cke_editable_themed.cke_contents_ltr.cke_show_borders").contents().find("p").contentEditable='false';
jQuery("iframe", "body .cke_editable.cke_editable_themed.cke_contents_ltr.cke_show_borders").contents().find("p").contentEditable='false';
var editor= jQuery("body", ".cke_editable.cke_editable_themed.cke_contents_ltr.cke_show_borders");
editor.val(editor.val().replace(/<p>/gi, "<p class='tiny_p'>"))
var editor= jQuery("body.cke_editable.cke_editable_themed.cke_contents_ltr.cke_show_borders");
editor.val(editor.val().replace(/<p>/gi, "<p class='tiny_p'>"))
yet if i hard code in the Chrome browser, contenteditable="false",
it works perfectly. So, how can i access that p tag and assign it this attribute?
It really depends on moment and how you want to access, one option to access directly from separate script.
CKEDITOR.instances[YOUR_INSTANCE].window.$.document.getElementById("your_p_tag")
Note, that it should be done after CKEDITOR initilized
UPDATE:
CKEDITOR.instances[YOUR_INSTANCE].window.$.document.body.firstChild
Can some one show how I can change the InnerHTML of the titles class to be the same as the alt attribute. For the actual website jarretonions.co.za
Thanks
$(document).ready(function() {
$(".pic").on("click", function() {
$(".modal").show();
var srclong = $(this).attr("src");
var srcshort = srclong.split("_");
var srcextension= srclong.split(".");
$(".modal img").attr("src", srcshort[0]+'.'+srcextension[1]);
************is it something like this********
var title = $(this).attr("alt");
$(".modal span").InnerHTML= title;
OR
document.getElementByClassName('titles').innerHTML = title;
})
+
echo
"<div class='art'>
<img class='pic' src='img/".$row["name"]."_tnail.jpg'
alt='".$row["name"]." • ".$row["year"]." • ".$row["type"]."'
height='auto' width='100%'/>
<div class='modal'>
<img class='big'/>
<span class='titles'></span>
</div>
</div>"
;
Since you're using JQuery, you can select those elements using $(".title") and change them directly. Something like so:
$(document).ready(function() {
$(".pic").on("click", function() {
$(".title").text( $(this).attr("alt") );
})});
Here's a fiddle: https://jsfiddle.net/wmjtfLja/1/
Note that if you have more than one element of class .title, they will all change. So you may want to select the title element by id or by relative path from the clicked image.
Realizing in advance, the danger of providing an answer that is not (superficially) fully aligned with the question, I was struck by the comment from melpomene, whom I initially thought was refering to things not existing in jquery.
melpomene is 100% correct, since getElementByClassName does not exist.
The correct syntax is getElementsByClassName.
Having said that, helloworld is also correct (syntax errors aside), since loading jquery for every little task is really redundent, and one can manipulate by class with little more half a dozen lines of pure javascript.
But, getting elements by class has dangers, since the return is a 'live' array.
For example, with dylan's original question, getting by class is only useful to return the first instance (the array length is just a guide of how many elemnts it applies to). Therefore, for dylan to make changes as he proposed, each requires its own button. (which also means, michael that I believe you are incorrect when you say it will affect all elements with same class name - oth, you are fully correct in noting that one should inpsect for other values (or change the class name) when running loops on the attribute).
Consider the following (on the fly class change);
function otf_cls_change(cls_original,cls_replace){
var a=document.getElementsByClassName(cls_original);
l=a.length;
if (l==0){return 0;}
do {
a[0].setAttribute('class',cls_replace);
a=document.getElementsByClassName(cls_original);
l=a.length;
} while (l>0);
}
This is effective for changing class names on the fly.
But, if we modify the code and
//change this a[0].setAttribute('class',cls_replace); // to
a[0].innerHTML='this_html';
It will cause the browser to hit an endless loop.
Why? because the live array returned by ElementByClass will only process the first item (even if you try to loop the array).
Therefore, while changing the class on the fly is fun and very do-able, I'd strongly suggest that using it to change any attrib that is not specific to the class id is a bad idea.
Changing the class attrib in conjunction with another attrib is fine.
For example,
a[0].innerHTML='this_html'; //do this first
a[0].setAttribute('class',cls_replace); //then this
The above will work to loop class defined elements.
On a point of massive personal hypocrisy, I do get annoyed when people ask for pure javascript solutions, and then some wing nut chimes in with jquery. I guess I'm doing the opposite here, since evidently, the question was jquery related, and here I am throwing out pure javascript. Sorry bout that.
btw, dylan, good luck with it. glad you bit back on the negative comment. Too many people here are terrified of offending, and wind up get bullied.
hth,
Gary
I am trying to replace some html text from some code with some new text using javascript and I have learned about Javascript HTML DOM which I believe is the way to do this; however, whenever write a method, nothing seems to change.
This is a line I am interested in changing. I want to change "Text here" to "Hello World!".
Text here
This the code I used
<script> document.getElementById("login_or_create_user_modal").innerHTML = "Hello World!"; </script>
My first concern is I have noticed that it is a data-reveal-id which is not the same as the usual id, is there a better method to use in this case? I couldn't find anything relating to data-reveal-id.
The other thing I am trying to change is to change the text cart to "Hello World!'. Again, the method I used does not do anything.
<script> document.getElementById("shopping_cart_btn").innerHTML = "Hello World!"; </script>
Am I using the right ID or am I just completely in the wrong path here?
Thanks :)
for document.getElementById() to work, you need an id attribute set, try:
Text here
change your "data-reveal-id" to just "id" and it should work
You're on the wrong path but you were heading the right direction. You just need to hop tracks and climb onto the document.querySelector() train, leaving document.getElementById behind for now.
getElementById will return an element whose id attribute equals the provided value; it won't look at any other attributes, like data-reveal-id.
querySelector instead uses CSS selectors to select an element. For examples of CSS selectors, refer the W3C documentation here: http://www.w3.org/TR/selectors/#selectors
You would use this like so:
document.querySelector("[data-reveal-id='shopping_cart_btn']").innerHTML = "Hello World!";
document.querySelector("[data-reveal-id='shopping_cart_btn']") is saying "get me the first element you can find whose data-reveal-id attribute is equal to shopping_cart_btn.
Here's a working example to prove I'm not crazy. When the JavaScript runs, it selects the div by its data-reveal-id attribute, then replaces its inner HTML:
document.querySelector("[data-reveal-id='something_random']").innerHTML = "New Text";
<div data-reveal-id="something_random">Original Text</div>
After much trial an error and some progress I still can't mange to change every instance of ,- with kr on my website.
I'm very much a beginner at JS and have pieced together the following code from several sources. Is the code the problem or something else?
function skrivkr() {
var skrivkr = $('div').text().replace(/\,-/g, 'kr');
$('p').html(skrivkr);
}
window.onload = skrivkr();
Update:
Thanks for the replies. The site loads jquery 1.10.7.
#Niet the Dark Absol: No, I don't want to put anything in p elements. How do I remove that part? I just want to find all ,- and simply replace with kr without changing any formatting.
Update
OK! Progress, kind of. The ENTIRE content of every <strong> and <dd> now changes to (0), instead of kr. With the odd exception of those tags including ,-. I haven't designed the site myself.
If it helps, one of the ,- appears in the following markup:
<a href="xxxx" rel="nofollow">
<span class="amount">1</span>
<span class="photo">
<img src="xxxx" alt="product name" width="62" height="42">
</span>
<span class="description">
Prtoduct name
<strong>4444,-</strong>
</span>
</a>
And the lastest script I'm applying is:
$(document).ready(function() {
$('strong, dd').html($('strong, dd').html().replace(/,-/g, 'kr'));
});
As has been mentioned innumerable times here on SO, do not try to manipulate the DOM as a string. Pain awaits.
Instead, traverse the DOM, finding text nodes, and perform whatever transformation you want to make on each text node. There are many ways to do that.
In your case, you have many problems, as mentioned already by some of the commenters and responders:
You're setting window.onload to undefined (the result of calling skrivkr), instead of to skrivkr itself.
You're extracting the text value of an element, which consists of the concatenation of all text down all levels, performing the replacement, then sticking it back in with html. This will wipe out all the element structure below.
Minor point, but there's no need to escape the comma in the regexp.
You're extracting the textual content of all div elements in the entire document, transforming it, then adding that back as the content of all p elements in the entire document. It's hard to imagine that's what you want to do.
You can update the content of each div like this
$(document).ready(function() {
$('div').each(function(){
var newText = $(this).html().replace(/,-/g, 'kr');
$(this).html(newText);
});
});
You can remove the var "newText = " and replace it with $(this).html($(this).html().replace(/,-/g, 'kr'));
The first example is easier to understand perhaps if you are new to programming.
You will, however only change the content of text placed in tags.
I would place the text to replace in a div with some predefine class, like "autoKronor", it would then look like this:
<div class="autoKronor">123,-</div>
and
$(document).ready(function() {
$('.autoKronor').each(function(){
var newText = $(this).html().replace(/,-/g, 'kr');
$(this).html(newText);
});
});
to en sure that only text you intended to change gets changed..
Example here: http://jsfiddle.net/akm1uw8h/2/
Also note the use of $(document).ready(); instead of window.onload. It does what you intended to do with window.onload.
if you really want to change EVERY single instance of ",-" to "kr" then you could do this:
$(document).ready(function() {
$('body').html($('body').html().replace(/,-/g, 'kr'));
});
But i strongly advice against the last example because it will be the slowest to compute and more importantly you might change stuff you don't intend to, like any script block inside the page body (with that i mean other javascripts)
In my HTML I have a content div that contains articles created by a php script and handled with JQuery and Javascript. With Javascript I collect those articles into an array with the 'getElementsByClassName' function.
The scripts and HTML I'm writing here are simplified. I need this array because I'm trying to make that if the length of the array is larger than 10, only 10 articles are displayed per page. So page 1 will be index 0 to 9 of the array, page 2 index 10 to 19, etc.
Now,
Take this html code.
<body>
<div id="content">
<div class="article">
<p>Article 1</p>
</div>
<div class="article">
<p>Article 2</p>
</div>
<div class="article">
<p>Article 3</p>
</div>
</content>
</body>
And this Javascript code.
$.post("getarticles.php",{ page:"home" } ,function(data){
//place the content
document.getElementById("content").innerHTML = jQuery.trim(data);
//put elements in array
arrArticles = document.getElementsByClassName("article");
alert(arrArticles.length);
document.getElementById("content").innerHTML = "";
alert(arrArticles.length);
})
The first alert gives me "3", which is correct.. But the second alert gives me "0". Why is the array losing it's elements after the elements have been put in it?
By the way, the 'data' variable is a string of HTML passed on by a php script.
For example: In the php script I have the code
echo "<div class="article"><p>Article 1</p></div><div class="article"><p>Article 2</p></div><div class="article"><p>Article 3</p></div>"
&
document.getElementById("contentWrap").innerHTML = "";
I know this is causing the problem, but I don't know why. Can anyone explain or provide an alternative?
Thanks in advance
getElementsByClassName() returns a dynamic array (actually a live NodeList) that will change dynamically if/when you modify the DOM. So, if you change the content with innerHTML and elements in that array are affected, the array will change automatically.
If you want to keep this list of elements and make it not be live (so it won't change when the DOM is changed), you can make a copy of the NodeList into a normal array (that is not dynamic) and once it is in a normal array, the references to the DOM elements will keep them from getting destroyed. It won't prevent them from getting changed if your code changes their contents, but it will keep them around even if your code caused them to get removed from the DOM.
One way to make a copy of the dynamic NodeList into a static array is like this:
// fetch dynamic NodeList
var items = document.getElementsByClassName("article");
// make static copy of NodeList into normal array
items = Array.prototype.slice.call(items);
Or, since your post is tagged with jQuery, you can just use jQuery in the first place which contains a static array of nodes that isn't affected by other changes in the DOM:
var items = $(".article");
It looks like document.getElementByClassName is returning a reference to the element array which is being updated when you change the mark up. Not sure why; perhaps somebody better informed than me can answer that.
Using jQuery to select the array worked for me:
var arrArticles = $(".article")
document.getElementsByClassName("article");
return [NodeList array], this array contain pointers to DOM elements
arrArticles = anotherArray;
this code do not create a copy of anotherArray, but it is make a pointer to values form anotherArray.
So when elements in anotherArray will be deleted, in arrArticles elements will dissapear also.