Copy divs with certain id's to targets with related id's - javascript

How do I copy the content from all divs with a certain class or a certain beginning of an id to a bunch of divs with related id's? The examples I found didn't go through multiple copies. I have a solution that is working ok but instead of calling each copy with the id I would like to make the logic better.
Here's what I have now.
HTML (handlebars template)
<!-- the id comes from handlebar content. There are many like this -->
<pre><code id="target-example-01" class='language-markup'></code></pre>
<!-- this content is put to place once handlebars has rendered the page -->
<div id="code-examples" style="display: none;">
<div class='code-example' id="source-example-01">
this is my a code example... there are many like me...
</div>
</div>
Javascript
var source = document.getElementById('source-example-01').innerHTML;
var target = document.getElementById('target-example-01');
if (target) target.innerHTML=source;
This works ok but I have 100 examples so I wouldn't like to have 300 lines of code to manually maintain just to copy the content. How do I go through all the divs with "code-example" class and copy their content to divs with a matching id. All the source divs will have the id="source-(example-identifier)" and all the target divs will have the id="target-(example-identifier)". I guess the class wouldn't be needed if the code would go through all items with the id beginning with "source-"

I would be old school and stick with using getElementsByClassName() but since the question is how to target divs will have the id="target-(example-identifier) you can use querySelectorAll()
document.querySelectorAll('div[id^="source-example-"]')
for more information about querySelectorAll()
Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.
So the output is very much like using getElementsByClassName()
If you have any questions please leave a comment below and I will reply as soon as possible.
How to target a specific tag with a class and id?
document.querySelectorAll('div.code-example[id^="source-example-"]')
You will still need to loop through the contend just like you would for returning elements by class name but this query selector will only return div elements with the class name code-example and contains source-example- in the id attribute.
function QuerySelector() {
var Selector=document.querySelectorAll('div.code-example[id^="source-example-"]');
for(var i=0; i<Selector.length; i++){
alert(Selector[i].innerHTML);
}
}
<div class="code-example" id="source-example-01">Content Line One. - with class and id </div>
<div class="code-example">Content Line Two. - with correct class but no ID</div>
<div class="code-example" id="source-example-02">Content Line Three. - with class and id </div>
<button onclick="QuerySelector()">Get</button>
I hope this helps. Happy coding!

How do I go through all the divs with "code-example" class and copy
their content to divs with a matching id
Assuming that index of code-example elements is same as that of targets, then try
var allCodeExamples = document.getElementsByClassName( "code-example" );
for ( var counter = 0; counter < allCodeExamples.length ; counter++ )
{
var index = ("0" + counter).slice( -2 );
var target = document.getElementById( "target-example-" + index );
target.innerHTML = allCodeExamples[counter].innerHTML;
}

You can make use of data attributes for this using jquery:
<!-- the id comes from handlebar content. There are many like this -->
<pre><code id="target-example-01" class='language-markup'></code></pre>
<!-- this content is put to place once handlebars has rendered the page -->
<div id="code-examples" style="display: none;">
<div class='code-example' id="source-example-01" data-target="#target-example-01">
this is my a code example... there are many like me...
</div>
</div>
$(function(){
var targetId;
$(".code-example").each(function(){
targetId = $(this).attr("data-target");
$(targetId).html($(this).html());
});
});

I realised it makes more sense to check which examples are on the page and fetch the content for their source id's. I added another class to the code-tags "target-example"
Here's the javascript (jquery would probably make it nicer looking)
var examples = document.getElementsByClassName('target-example');
var i;
var id;
for (i = 0; i < examples.length; i++) {
id = examples[i].id;
var source = document.getElementById('source-'+id).innerHTML;
if (source) examples[i].innerHTML=source;
}

Related

If URL contains this string then hide all divs with this class/id (loop script)

I am trying to hide some divs when url contains an specific string.
For example, i have this code that hides the first div:
<div id="ficha">Hello</div>
<div id="ficha">world</div>
<div id="ficha">...</div>
<script>
if (/info|mapo/.test(window.location.href)) {
document.getElementById('ficha').style.display = 'none';
}
</script>
URLs:
www.example.com/all ------> Not hide the div
www.example.com/info-----> Hide the div
www.example.com/mapo---> Hide the div
The first problem with the script is that it only hides the first div saying Hello, but i want to hide all the divs. So, i think it's necessary to do a loop... ¿how can i do that?
The second thing is running two different scripts to hide different divs according the url string content.
Maybe this can be achived by making an else function. Always the loop its necessary and even better if it's executed after load page.
For example:
<div id="ficha">Hello</div>
<div id="ficha">Hello2</div>
<div id="ficha2">world</div>
<div id="ficha2">...</div>
<!-- First script hides divs with id="ficha" if url string has "info" or "mapo" -->
<script>
if (/info|mapo/.test(window.location.href)) {
document.getElementById('ficha').style.display = 'none';
}
</script>
<!-- Second script hides divs with id="ficha2" if url string has "all" -->
<script>
if (/all/.test(window.location.href)) {
document.getElementById('ficha2').style.display = 'none';
}
</script>
The code will be execute in Database Activity of Moodle.
Thanks in advance.
This script will help you.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload = function () { //The function to execute when the page is loaded
var string_contain = ''; //Set this as your string
var url = window.location.href;
if(url.indexOf(string_contain) >= 0) { //If url contains then...
var x = document.getElementsByClassName("your_class"); //Create an array that contains your divs with your_class class
for(var a = 0;a<x.length;a++) { //Do some stuff for each value of the array
x[a].style.display = 'none';
}
}
}
</script>
</head>
<body>
<div class="your_class"></div>
</body>
</html>
Remeber that the ID is associated with just one element, so it won't work if you're trying to access more than one element.
You've got a few issues here:
First, like user adeneo mentioned in their comment, you cannot share IDs. Classes, however, can be shared so you probably want your <div> elements to say class="ficha".
Second, you want to hide or show divs based off of a string in the URL, but your URLs are composed of unique paths. You're trying to hide divs, when you should just be building the pages differently. Unless there's more information you need to add about this.
www.example.com/mapo is, at least in the representation you've provided, a different HTML page from www.example.com/info so why not build them as separate pages rather than going through unnecessary logic to show and hide <div> elements?
The third issue: you don't want a for loop so much as a for-each loop. This first question will give you direction on how to select all elements with the specified class:
JavaScript get elements by class name and tag name
Then using the array you've selected from the above information, you can use Javascript Documentation for using forEach on arrays to change your elements' visibility.
Since its not unique, a CSS class would be more appropriate. Something like this should work:
function hideItemsByClass(className){
var matchedItems = document.getElementsByClassName(className);
for(var i = 0; i < matchedItems.length; i++){
matchedItems[i].style.display = 'none';
}
}

Dynamically name divs in partial for use later?

I have a partial view which contains a div, then that div id is currently static. If I use this partial view multiple times, my Javascript class only loads the first div. What is the MVC convention to give these divs a unique ID so this doesn't happen any longer? Would generating a random number work?
Sample code:
<div id="test"></div>
<script type="text/javascript">
var loader = new Class('test');
</script>
Ideally I'd like it so every time I render the partial view, an incrementing number is appended to id="test.
Seems like there are many ways to tackle this. It looks like it is important that you be able to reference the additional element in a JS class after loading it. There are a couple of approaches that come to mind.
1) Add div dynamically via JS ( I am using jquery here to simplify the task ):
add to your class definition:
<script type='text/javascript' >
/* you need to add a static method to your class to create
a unique id.
Note that this should not be part of your partial view - it
is only defined once - wherever you have defined your class.
*/
Class.idNum = 0;
Class.uniqueId = function() { return 'MyDiv_' + idNum++; };
</script>
partial becomes:
<script type='text/javascript' >
// you need to have a
var newId = Class.uniqueId();
var newDiv = jQuery('<div id="' + newId + '" />' );
// figure out where you need to append it, e.g. to the html body:
jQuery('body').append( newDiv );
var loader = new Class( newId );
</script>
2) However, a simpler method might be avoiding ids altogether, which is more typical in this kind of dynamic code in my experience. In this solution, you add all your divs via partials, identify them as a group with a unique class name, and then reference that class name to grab all those divs as a group and iterate over them to create your classes. Of course, you would have to rewrite your class to refer to these divs by their DOM elements rather than an ID attribute.
Partial becomes:
<div class='MyDescriptiveClassName' ></div>
Then, after all partials have been added, you would have something like the following javascript:
<script type='text/javascript' >
jQuery('.MyDescriptiveClassName').each( function( index, elem ) {
// pass in the DOM element for accessing this div.
var loader = new Class( elem );
});
</script>
Hope that helps.

Extract content from <div> tags

I'm wondering how I could 'extract' the content from a set of div tags, for further use (like emailing or displaying elsewhere). The tricky part is that the content in the div's is only made after the page has loaded.
This is the div:
<div class='simpleCart_items'></div>
I have an understanding of javascript and php,
Thanks in advance!
If you use jQuery, very simply:
var content = $('.simpleCart_items').html();
This, assuming you have only 1 element with that classname. Otherwise, you could get other content
Wrap this with the ready() function in jQuery. Please refer to the documentation
You'll have to get the content once it's there, as you can't get something that doesn't exists. With that in mind, you'd get it the same way you would any other content.
var els = document.querySelectorAll('.simpleCart_items'); // nodelist
for (var i=0; i<els.length; i++) {
console.log( els[i].innerHTML )
}

Changing getElementById to getElementsByClassName

I am sure is a common problem in JS, i have created resizing function using JS, initially this function was only going to be used on one item of my site, however now i have chosen to use it on multiple items. My JS function currently uses document.getElementById(id); however i want to change this so it looks out for the class name .resize. How can this be done?
Below is a snippet of my JS
function ebi(id){
return document.getElementById(id);
}
if(ebi('resize')
.complete==true){
iscale(ebi(''));
}
ebi('resize')
.onload=function(){iscale(this);
}
function iscale(o){
//alert(o.width);
var sar=o.width/o.height;
var tar=1,tiw,tih,xoff,yoff;
if(o.width<=425&&o.height<=467){
tiw=o.width;
tih=o.height;
}else if(tar>sar){
tiw=425*sar;
tih=467;
}
else{
tiw=425;
tih=467/sar;
}
xoff=(680-tiw)>>1;
yoff=(209-tih)>>1;
//alert(xoff);
o.width=tiw;o.height=tih;
o.style.top=yoff+"px";
o.style.left=xoff+"px";
}
function $(id){return document.getElementById(id);}
html
<section id="homeSlide" class="shadow">
<img id="resize"class='opaque' src="http://www.colette.fr/media/push/pony_01239.jpg" />
<img id="resize" src="http://www.colette.fr/media/push/EGIFT_01234.jpg" />
<img id="resize" src="http://www.colette.fr/media/push/swa_mmm_001255.jpg" />
</section>
At the moment the resize function only works for the first image, however the other images do not resize. Before anyone attacks me about web standards the id's in the img tags were just to test the function.
id have to be unique, that's why this didn't works.
You can use document.getElementsByClassName() (as you thought) : simply add class="resize" (instead of id="resize") and use that kind of loop:
function callResize()
{
var elements = document.getElementsByClassName("resize");
for (var i=0;i<elements.length;i++)
{
var element = elements[i];
// do things with element
iscale(element);
}
}
document.getElementById('homeSlide').onload = function(){callResize();}
the point is id should be unique and to do what you want why don't you use jQuery. using jQuery you can easily do what you want, using this
jQuery("#homeSlide>img")
and you can also add this:
jQuery("#homeSlide>img").each(function(imgNode){
resize(imgNode);
});
but if you want to do it without jQuery, as far as some functions like getElementsByClassName and getElementsByTagName are not cross browser, you'd better try this:
var homeSlide = document.getElementById('homeSlide');
var myImgNodes = [];
for(var i=0;i<homeSlide.childNodes.length;i++){
var childNode = homeSlide.childNodes[i];
if(childNode.nodeType==1 && childNode.tagName.toLowerCase()=="img"){
myImgNodes.push(childNode);
}
}
afterwards myImgNodes would be exactly what you want.
I just changed your fiddle example and tried not to change your functionality, you can check this out, it perfectly works. This is your updated jsfiddle DEMO
First, an ID has to be unique in your HTML document. But in your example code you assign the ID "resize" three times. Just replace the ID from all three elements and add class="resize".
Second, I suggest to use the jQuery.each() method to iterate over the returned collection instead of a loop.
Example:
var elements = document.getElementsByClassName("resize")
jQuery.each(elements, function(element) {
iscale(element)
})

Prototype function different id elements of the same class

I'm making this prototype script to work:
function removing () {
*var ids = $$('.class').collect(function(el) { return el.id; });* //array of ids, not used by now
var data = $$('.class').pluck('innerHTML');
var wanted_count = 10;
var output = cutHtmlString(data, wanted_count);
$$('.class').invoke('replace', output + '...');
}
on this markup:
<div class="class" id="id1">content 1</div>
<div class="class" id="id2>content 2</div>
<div class="class" id="id3>content 3</div>
cutHtmlString is a function that cut html strings keeping tags and I want to apply it to every different div content. I create 'data' variable (by innerHTML) from general $$(.class) and then I execute cutting by a words count (var wanted_count) into 'output' var.At the end I replace the original element (by $$.class again) with its new cut content.All works great except for one issue: using only $$(class) makes only the first element content to be considered and replaced to every others.I need to identify elements by ids too, I guess..thus I added the commented function upon (collect) but I don't know how to join my target..By now I only got to this results:
this is the content of firts 'class'
div...(cut)this is the content of firts 'class' div...
this is the content of firts 'class' div...
while I want to get:
this is the content of first 'class'
div...
this is the content of second 'class' div...
this is the content of third 'class' div...
thanks guys and an appreciation to this great community whole
I believe you are mixing working on a collection of elements with working on a single element. It's been a while since I've been in Prototype, but have you tried to work on very individually so output is scoped to the element you are replacing:
function removing () {
var data, output, wanted_count = 10;
$$('.class').each(function(element){
output = cutHtmlString(element.innerHTML, wanted_count);
element.replace(output + '...');
});
}
Invoke only woks if your padding the same variables to each element. You need to use each.
Also I think you want to use update and not replace.
try this.
function removing() {
$$('.class').each(function(el){
var output = cutHtmlString(el.innerHTML, 10);
el.update(output + '...');
});
}

Categories

Resources